【问题标题】:Setting focus on an HTML input box on page load在页面加载时将焦点设置在 HTML 输入框上
【发布时间】:2011-03-23 22:38:16
【问题描述】:

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

非常感谢您的帮助:-)

【问题讨论】:

    标签: javascript html focus onload autofocus


    【解决方案1】:

    这一行:

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

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

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

    【讨论】:

    • 这会真正设置输入焦点吗?您在哪个浏览器上试用过?
    • @PeterMortensen 当我 9 年前在 Firefox、chrome 和 ie 上进行测试时:)
    【解决方案2】:

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

    修复:-

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

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

    【讨论】:

      【解决方案3】:

      你也可以使用:

      <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();
      }
      

      【讨论】:

        【解决方案4】:

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

        <input type="text" name="fname" autofocus>
        
        猜你喜欢
        • 2011-11-13
        • 1970-01-01
        • 2011-02-12
        • 2011-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-23
        相关资源
        最近更新 更多