110

我试图在页面加载时将默认焦点设置在输入框上(例如: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>

为什么这不起作用,而这工作正常?

<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>

非常感谢您的帮助:-)

4

4 回答 4

351

您可以使用 HTML5 的 autofocus 属性(适用于除 IE9 及以下的所有当前浏览器)。仅当它是 IE9 或更早版本或其他浏览器的旧版本时才调用您的脚本。

<input type="text" name="fname" autofocus>
于 2010-08-01T19:42:33.670 回答
38

这一行:

<input type="password" name="PasswordInput"/>

应该有一个id属性,像这样:

<input type="password" name="PasswordInput" id="PasswordInput"/>
于 2010-08-01T19:32:26.460 回答
5

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

使固定 :-

function FocusOnInput() {
    var element = document.getElementById('txtContactMobileNo');
    element.focus();
    setTimeout(function () { element.focus(); }, 1);
}

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

于 2016-03-31T10:44:40.353 回答
2

您还可以使用:

<body onload="focusOnInput()">
    <form name="passwordForm" action="verify.php" method="post">
        <input name="passwordInput" type="password" />
    </form>
</body>

然后在你的 JavaScript 中:

function focusOnInput() {
    document.forms["passwordForm"]["passwordInput"].focus();
}
于 2015-09-16T17:11:55.533 回答