2010-08-01 64 views
80

我試圖在頁面加載時設置輸入框的默認焦點(例如:google)。 我的網頁很簡單,但我無法弄清楚如何做到這一點。在頁面加載時將焦點設置爲HTML輸入框

這是我到目前爲止有:

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

幫助深表感謝:-)

回答

33

這條線:

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

應該有一個ID屬性,就像這樣:

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

你也可以使用HTML5的自動對焦屬性(適用於除IE9和Bel之外的所有當前瀏覽器OW)。只有在IE9或更早的版本或其他瀏覽器的舊版本中調用腳本。

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

「適用於所有的主流瀏覽器」 - 即真的取決於您對「所有當前瀏覽器」的定義。 – 2010-08-01 20:30:52

+7

ie9:http://stackoverflow.com/questions/8280988/how-to-make-input-autofocus-in-internet-explorer – jedierikb 2013-06-11 14:06:35

+0

@BhaveshGangani ['autofocus' is不支持Internet Explorer 9和更早版本。](http://www.w3schools.com/tags/att_input_autofocus.asp) – 2014-09-09 13:58:40

0

您還可以使用:

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

這是使用IE瀏覽器的常見問題之一,解決很簡單。 將.focus()兩次添加到輸入。

修復: -

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

而且在$調用FocusOnInput()(文件)。就緒(函數(){.....};

相關問題