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

就像这样:

<body onload='setFocusToTextBox()'>

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

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

当前回答

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

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

检查一下是否有帮助。

其他回答

如前所述,文档。表单也有用。

function setFocusToTextBox( _element ) {
  document.forms[ 'myFormName' ].elements[ _element ].focus();
}

setFocusToTextBox( 0 );
// sets focus on first element of the form

如果你的<input>或<textarea>有属性id=mytext,那么使用

mytext.focus();

函数setFocusToTextBox() { mytext.focus (); } <身体onload = ' setFocusToTextBox () > < >形式 <input type="text" id="mytext"/> > < /形式 < /身体>

<input type="text" class="word"> //html code

let theinput = document.querySelector(".word"); //Get the input 
 theinput.focus(); // focus on input 
   

窗口。Onload是最初放置焦点 Onblur是将焦点放在文本区域外,或避开文本区域 模糊

    <textarea id="focus"></textarea>
    <script>
     var mytexarea=document.getElementById("focus");
    window.onload=function()
    {
   
    mytexarea.focus();
    
    }
    

    </script>

不管怎样,你可以在HTML5兼容浏览器上使用自动聚焦属性。甚至可以在IE版本10上使用。

<input name="myinput" value="whatever" autofocus />