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


95

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

非常感谢帮助:-)

Answers:


36

这行:

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

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

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

这实际上会设置输入焦点吗?您尝试使用哪个浏览器?
彼得·莫滕森

@PeterMortensen在我9年前测试时使用的是Firefox,chrome和:)
Saikios


5

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

修复:-

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

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


1

您还可以使用:

<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();
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.