问题
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