我正在尝试在页面加载时将默认焦点设置在输入框上(例如: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>
非常感谢帮助: - )
答案 0 :(得分:302)
您可以使用HTML5的自动对焦属性(适用于除IE9及以下版本的所有当前浏览器)。仅在IE9或更早版本或其他浏览器的旧版本时调用您的脚本。
<input type="text" name="fname" autofocus>
答案 1 :(得分:35)
这一行:
<input type="password" name="PasswordInput"/>
应具有 id 属性,如下所示:
<input type="password" name="PasswordInput" id="PasswordInput"/>
答案 2 :(得分:5)
这是IE的常见问题之一,修复此问题很简单。 将.focus()两次添加到输入。
修复: -
(function() {
function loadjQuery(url, callback) {
<same as above, but without the noConflict() call>
}
function doSomethingInOtherScript() {
jQuery(document).ready(....);
}
loadjQuery("https://code.jquery.com/jquery-X.Y.Z.min.js", doSomethingInOtherScript);
})();
并在$(document).ready(function(){.....};
上调用FocusOnInput()答案 3 :(得分: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();
}