Answers:
如果您使用的是jquery:
$(function() {
$("#Box1").focus();
});
或原型:
Event.observe(window, 'load', function() {
$("Box1").focus();
});
或纯JavaScript:
window.onload = function() {
document.getElementById("Box1").focus();
};
尽管请记住,这将替换其他加载处理程序,所以请在Google中查找addLoadEvent()以获取添加加载处理程序而不是替换的安全方法。
在HTML中,所有表单字段都有一个autofocus
属性。在Dive Into HTML 5中有一个很好的教程。不幸的是,低于10的IE版本当前不支持它。
要使用HTML 5属性并使用JS选项,请执行以下操作:
<input id="my-input" autofocus="autofocus" />
<script>
if (!("autofocus" in document.createElement("input"))) {
document.getElementById("my-input").focus();
}
</script>
不需要jQuery,onload或事件处理程序,因为JS位于HTML元素下方。
编辑:另一个优点是,它在某些浏览器中可以关闭JavaScript,并且当您不想支持较旧的浏览器时可以删除JavaScript。
编辑2:Firefox 4现在支持该autofocus
属性,只是不支持IE。
autofocus="aufofocus"
?您提供的所有链接只是说要添加属性:autofocus
。
attribute="value"
,布尔属性是很常见的。HTML5附带了“空属性语法”,我们删除了冗余。现在我们可以做<input checked disabled autofocus data-something>
您需要使用javascript:
<BODY onLoad="document.getElementById('myButton').focus();">
@Ben指出,您不应添加这样的事件处理程序。虽然这是另一个问题,但他建议您使用此功能:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
然后在页面上调用addLoadEvent并引用一个将焦点设置到所需文本框的函数。
您可以通过以下方式使用jquery轻松完成此操作:
<script type="text/javascript">
$(document).ready(function () {
$("#myTextBoxId").focus();
});
</script>
通过在中调用此函数$(document).ready()
。
这意味着此功能将在DOM准备就绪时执行。
有关READY函数的更多信息,请参见:http : //api.jquery.com/ready/
使用普通的html和javascript
<input type='text' id='txtMyInputBox' />
<script language='javascript' type='text/javascript'>
function SetFocus()
{
// safety check, make sure its a post 1999 browser
if (!document.getElementById)
{
return;
}
var txtMyInputBoxElement = document.getElementById("txtMyInputBox");
if (txtMyInputBoxElement != null)
{
txtMyInputBoxElement.focus();
}
}
SetFocus();
</script>
对于那些使用.net框架和asp.net 2.0或更高版本的用户而言,它是微不足道的。如果您使用的是较早版本的框架,则需要编写一些与上述类似的javascript。
在您的OnLoad处理程序中(如果使用的是Visual Studio提供的股票页面模板,通常为page_load),您可以使用:
C#
protected void PageLoad(object sender, EventArgs e)
{
Page.SetFocus(txtMyInputBox);
}
VB.NET
Protected Sub PageLoad(sender as Object, e as EventArgs)
Page.SetFocus(txtMyInputBox)
End Sub
(*注意,我从通常为Page_Load的函数名称中删除了下划线字符,因为在代码块中,该字符拒绝正确渲染!我在标记文档中看不到如何使下划线呈现为未转义。)
希望这可以帮助。
我有一个稍微不同的问题。我想要autofocus
,但是,想要placeholder
保留文本,跨浏览器。有些浏览器会placeholder
在字段集中后立即隐藏文本,有些会保留文本。我不得不让占位符留在跨浏览器中,这会产生奇怪的副作用,或者必须停止使用autofocus
。
因此,我侦听了根据body标签键入的第一个键,并将该键重定向到目标输入字段。然后,所有涉及的事件处理程序都会被杀死,以保持环境整洁。
var urlInput = $('#Url');
function bodyFirstKey(ev) {
$('body').off('keydown', bodyFirstKey);
urlInput.off('focus', urlInputFirstFocus);
if (ev.target == document.body) {
urlInput.focus();
if (!ev.ctrlKey && !ev.metaKey && !ev.altKey) {
urlInput.val(ev.key);
return false;
}
}
};
function urlInputFirstFocus() {
$('body').off('keydown', bodyFirstKey);
urlInput.off('focus', urlInputFirstFocus);
};
$('body').keydown(bodyFirstKey);
urlInput.focus(urlInputFirstFocus);