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

122

我正在尝试在页面加载时设置输入框的默认焦点(例如:谷歌)。

我的页面非常简单,但我无法弄清如何做到这一点。

这是我已经得到的:

<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个回答

379

您可以使用HTML5的自动对焦属性(适用于除IE9及以下版本之外的所有当前浏览器)。仅在IE9或更早版本的浏览器或其他浏览器的较旧版本中调用您的脚本。

<input type="text" name="fname" autofocus />

7
我可以进行翻译。以下是需要翻译的内容:ie9: https://dev59.com/M13Va4cB1Zd3GeqPCqlK - jedierikb
4
以下是“自动对焦”功能的兼容性表格链接:https://caniuse.com/#feat=autofocus - Oreo
如果没有这个网站,我已经90岁了,因为我会把所有时间都花在研究上。 - aremmell

40

这一行:

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

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

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

1
那真的会设置输入焦点吗?你在哪个浏览器上尝试过? - Peter Mortensen
1
@PeterMortensen 当我在9年前测试时,使用的是Firefox、Chrome和IE :) - Saikios

6

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

修复方法:

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

在$(document).ready(function () {.....};上调用FocusOnInput()函数。


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接