2010-08-01 69 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()(文件)。就绪(函数(){.....};

相关问题