Javascript 如何进行现场自动对焦?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4676321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I make a field autofocus?
提问by lisovaccaro
I need this field to be focused when the user opens the page. I don't know if it changes anything but it's inside a modal window I load from a PHP file.
当用户打开页面时,我需要关注这个字段。我不知道它是否有任何改变,但它位于我从 PHP 文件加载的模式窗口内。
Is there an easy way to do it?
有没有简单的方法来做到这一点?
回答by Michael Irigoyen
Using JavaScript, you can achieve this:
使用 JavaScript,您可以实现:
document.onload = function() {
document.getElementById("question-box-0").focus();
}
回答by Day
JavaScript autofocusers (as given in the other answers here) will work but can be annoying for some users. For example, if you focus a different field while a page is still loading, the JavaScript may "help" you by moving the focus and making you type in the wrong field. This questionon ux.stackexchange.com enumerates some more drawbacks.
JavaScript 自动对焦器(如此处的其他答案中所述)可以工作,但对某些用户来说可能会很烦人。例如,如果您在页面仍在加载时聚焦不同的字段,JavaScript 可能会“帮助”您移动焦点并使您输入错误的字段。ux.stackexchange.com 上的这个问题列举了更多的缺点。
To prevent this, HTML5 has introduced an autofocus
attributefor form elements that means the behaviour will be consistently implemented by the browser itself, and can be turned off for users that find it irritating. Of course, this isn't supported by all browsers yet. For more info, see the section on autofocus fieldsin Mark Pilgrim's excellent Dive Into HTML5book.
为了防止这种情况,HTML5为表单元素引入了一个autofocus
属性,这意味着该行为将由浏览器本身始终如一地实现,并且可以将其关闭以让用户感到恼火。当然,这不是所有浏览器都支持的。有关更多信息,请参阅Mark Pilgrim 出色的Dive Into HTML5书中有关自动对焦字段的部分。
回答by Martin Jespersen
<html>
<head>
<script>
document.onload = function() {
document.getElementById('question-box-0').focus();
};
</script>
</head>
<body>
...
</body>
</html>