How do I make a field autofocus?

你离开我真会死。 提交于 2020-01-30 05:11:06

问题


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.

Is there an easy way to do it?


回答1:


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 question on ux.stackexchange.com enumerates some more drawbacks.

To prevent this, HTML5 has introduced an autofocus attribute for 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 fields in Mark Pilgrim's excellent Dive Into HTML5 book.




回答2:


Using JavaScript, you can achieve this:

document.onload = function() {  
  document.getElementById("question-box-0").focus();
}



回答3:


<html>
<head>
<script>
document.onload = function() {
 document.getElementById('question-box-0').focus();
};
</script>
</head>
<body>
...
</body>
</html>


来源:https://stackoverflow.com/questions/4676321/how-do-i-make-a-field-autofocus

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!