我有一个网页表单的文本框。如何在默认情况下设置文本框的焦点?

就像这样:

<body onload='setFocusToTextBox()'>

有人能帮帮我吗?我不知道如何用JavaScript设置文本框的焦点。

<script>
  function setFocusToTextBox(){
    //What to do here
  }
</script>

当前回答

这个例子对我很有用

$(document).ready(function () {
document.getElementById('TextBox').focus();
}

其他回答

通常当我们关注文本框时,我们也应该滚动到视图

function setFocusToTextBox(){
    var textbox = document.getElementById("yourtextbox");
    textbox.focus();
    textbox.scrollIntoView();
}

检查一下是否有帮助。

如果你的代码是:

<input type="text" id="mytext"/>

如果你正在使用JQuery,你也可以使用这个:

<script>
function setFocusToTextBox(){
    $("#mytext").focus();
}
</script>

请记住,必须首先绘制输入$(document).ready()

这个例子对我很有用

$(document).ready(function () {
document.getElementById('TextBox').focus();
}

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.

试试这个:

$('.modal').on('shown.bs.modal', function () {
        setTimeout(function() {
                $("input#yourFieldId").addClass('modal-primary-focus').focus();
            },
            500);
    });