在页面加载时将焦点设置在HTML输入框上

Chr*_*ris 95 html javascript focus onload autofocus

我正在尝试在页面加载时将默认焦点设置在输入框上(例如:google).我的页面非常简单,但我无法弄清楚如何做到这一点.

这是我到目前为止所得到的:

<html>
<head>
 <title>Password Protected Page</title>

 <script type="text/javascript">
 function FocusOnInput()
 {
 document.getElementById("PasswordInput").focus();
 }
 </script>

 <style type="text/css" media="screen">
  body, html {height: 100%; padding: 0px; margin: 0px;}
  #outer {width: 100%; height: 100%; overflow: visible; padding: 0px; margin: 0px;}
  #middle {vertical-align: middle}
  #centered {width: 280px; margin-left: auto; margin-right: auto; text-align:center;}
 </style>
</head>
<body onload="FocusOnInput()">
 <table id="outer" cellpadding="0" cellspacing="0">
  <tr><td id="middle">
   <div id="centered">
  <form action="verify.php" method="post">
   <input type="password" name="PasswordInput"/>
  </form>
   </div>
  </td></tr>
 </table>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

为什么这种方法不能正常工作呢?

<html>
<head>
<script type="text/javascript">
function FocusOnInput()
{
     document.getElementById("InputID").focus();
}
</script>
</head>

<body onload="FocusOnInput()">
  <form>
       <input type="text" id="InputID">
  </form>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)

非常感谢帮助:-)

Lin*_*ars 312

并且您可以使用HTML5的自动聚焦属性(适用于除IE9及更低版本之外的所有当前浏览器).仅在IE9或更早版本或其他浏览器的旧版本时调用您的脚本.

<input type="text" name="fname" autofocus>
Run Code Online (Sandbox Code Playgroud)

  • ie9:http://stackoverflow.com/questions/8280988/how-to-make-input-autofocus-in-internet-explorer (7认同)
  • 这是**自动对焦的兼容性表**:https://caniuse.com/#feat = autofocus (4认同)

Sai*_*ios 35

这一行:

<input type="password" name="PasswordInput"/>
Run Code Online (Sandbox Code Playgroud)

应该有一个id属性,如下所示:

<input type="password" name="PasswordInput" id="PasswordInput"/>
Run Code Online (Sandbox Code Playgroud)


小智 5

这是IE的常见问题之一,因此修复很简单。将.focus()两次添加到输入中。

修复:-

function FocusOnInput() {
    var element = document.getElementById('txtContactMobileNo');
    element.focus();
    setTimeout(function () { element.focus(); }, 1);
}
Run Code Online (Sandbox Code Playgroud)

然后在$(document).ready(function(){.....};上调用FocusOnInput();