我有一个网页表单的文本框。如何在默认情况下设置文本框的焦点?
就像这样:
<body onload='setFocusToTextBox()'>
有人能帮帮我吗?我不知道如何用JavaScript设置文本框的焦点。
<script>
function setFocusToTextBox(){
//What to do here
}
</script>
我有一个网页表单的文本框。如何在默认情况下设置文本框的焦点?
就像这样:
<body onload='setFocusToTextBox()'>
有人能帮帮我吗?我不知道如何用JavaScript设置文本框的焦点。
<script>
function setFocusToTextBox(){
//What to do here
}
</script>
当前回答
我以前经常用这个:
<html>
<head>
<script type="text/javascript">
function focusFieldOne() {
document.FormName.FieldName.focus();
}
</script>
</head>
<body onLoad="focusFieldOne();">
<form name="FormName">
Field <input type="text" name="FieldName">
</form>
</body>
</html>
也就是说,你可以在HTML 5中使用autofocus属性。
请注意:我想更新这个旧线程,显示所问的示例,以及更新的,更容易的更新,供那些仍然在读这篇文章的人使用。;)
其他回答
<input type="text" class="word"> //html code
let theinput = document.querySelector(".word"); //Get the input
theinput.focus(); // focus on input
这样做。
如果你的元素是这样的…
<input type="text" id="mytext"/>
你的剧本应该是
<script>
function setFocusToTextBox(){
document.getElementById("mytext").focus();
}
</script>
对于简单的Javascript,试试下面的代码:
window.onload = function() {
document.getElementById("TextBoxName").focus();
};
如果你的代码是:
<input type="text" id="mytext"/>
如果你正在使用JQuery,你也可以使用这个:
<script>
function setFocusToTextBox(){
$("#mytext").focus();
}
</script>
请记住,必须首先绘制输入$(document).ready()
Thought of sharing some edge cases for this subject. If your content is reloading (example dynamic DOM loading results from API and setting focus on first item of results) adding attribute autofocus will not be your solution, it works only on first load, second DOM change will not work but works fine in static DOM or single page load. If you have Dynamic component loading data simple .focus() will fail due to triggering focus on element not created yet by the time focus() is or blur not complete yet by DOM. For this case expected is to add delay time (setTimeout function) to give a time for focus to apply to new created or recreated element in DOM. My case was to load data from API and get focus on first result. Adding var el = document.getElementById(focusId); el.focus(); solved the issue so DOM completes blur without adding delay.