How do I make a field autofocus?
I need this fi开发者_运维技巧eld 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?
Using JavaScript, you can achieve this:
document.onload = function() {
document.getElementById("question-box-0").focus();
}
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.
<html>
<head>
<script>
document.onload = function() {
document.getElementById('question-box-0').focus();
};
</script>
</head>
<body>
...
</body>
</html>
精彩评论