簡體   English   中英

在頁面加載時將焦點設置在HTML輸入框上

[英]Setting focus on an HTML input box on page load

我正在嘗試在頁面加載時將默認焦點設置在輸入框上(例如: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>

非常感謝幫助:-)

並且您可以使用HTML5的自動聚焦屬性(適用於除IE9及更低版本之外的所有當前瀏覽器)。 僅在IE9或更早版本或其他瀏覽器的舊版本時調用您的腳本。

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

這一行:

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

應該有一個id屬性,如下所示:

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

這是IE的常見問題之一,修復此問題很簡單。 將.focus()兩次添加到輸入。

修復: -

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

並在$(document).ready(function(){.....}上調用FocusOnInput();

你也可以使用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM