本文翻译自:JavaScript set focus to HTML form element
I have a web form with a text box in it. 我有一个带有文本框的Web表单。 How do I go about setting focus to the text box by default? 如何默认将焦点设置到文本框?
Something like this: 像这样的东西:
<body onload='setFocusToTextBox()'>so can anybody help me with it? 所以有人可以帮我吗? I don't know how to set focus to the text box with JavaScript. 我不知道如何使用JavaScript将焦点设置到文本框。
<script> function setFocusToTextBox(){ //What to do here } </script>参考:https://stackoom.com/question/1BQjQ/JavaScript将焦点设置为HTML表单元素
Do this. 做这个。
If your element is something like this.. 如果你的元素是这样的..
<input type="text" id="mytext"/>Your script would be 你的脚本会是
<script> function setFocusToTextBox(){ document.getElementById("mytext").focus(); } </script>For plain Javascript, try the following: 对于普通Javascript,请尝试以下操作:
window.onload = function() { document.getElementById("TextBoxName").focus(); };Usually when we focus on a textbox, we should also scroll into view 通常当我们关注文本框时,我们也应该滚动到视图中
function setFocusToTextBox(){ var textbox = document.getElementById("yourtextbox"); textbox.focus(); textbox.scrollIntoView(); }Check if it helps. 检查它是否有帮助。
For what it's worth, you can use the autofocus attribute on HTML5 compatible browsers. 对于它的价值,您可以在兼容HTML5的浏览器上使用autofocus属性。 Works even on IE as of version 10. 从版本10开始,甚至可以在IE上运行。
<input name="myinput" value="whatever" autofocus />As mentioned earlier, document.forms works too. 如前所述, document.forms也有效。
function setFocusToTextBox( _element ) { document.forms[ 'myFormName' ].elements[ _element ].focus(); } setFocusToTextBox( 0 ); // sets focus on first element of the form