如何使用 JavaScript 将焦点设置在 HTML 表单中的元素上?

2022-01-13 00:00:00 textbox focus javascript html

我有一个带有文本框的网络表单.默认情况下如何将焦点设置到文本框?

I have a web form with a text box in it. How do I go about setting focus to the text box by default?

类似这样的:

<body onload='setFocusToTextBox()'>

所以有人可以帮我吗?我不知道如何使用 JavaScript 将焦点设置到文本框.

so can anybody help me with it? I don't know how to set focus to the text box with JavaScript.

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

推荐答案

这样做.

如果你的元素是这样的..

If your element is something like this..

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

你的脚本是

<script>
function setFocusToTextBox(){
    document.getElementById("mytext").focus();
}
</script>

相关文章