Html 如何在加载网页时将文本框设置为已处于焦点
我希望我的网页加载时文本框处于焦点位置。如果你去google.com,你可以看到文本框已经在焦点上了。这就是我想要的 这是我的表格:Html 如何在加载网页时将文本框设置为已处于焦点,html,Html,我希望我的网页加载时文本框处于焦点位置。如果你去google.com,你可以看到文本框已经在焦点上了。这就是我想要的 这是我的表格: <form id="searchthis" action="#" style="display:inline;" method="get"> <input id="namanyay-search-box" name="q" size="40" x-webkit-speech/> <input id="namanyay-sear
<form id="searchthis" action="#" style="display:inline;" method="get">
<input id="namanyay-search-box" name="q" size="40" x-webkit-speech/>
<input id="namanyay-search-btn" value="Search" type="submit"/>
或者您可以在$(window.load()
为您的文本输入提供属性。它有相当好的浏览器支持,但并不完美。我们可以很容易地多填充此功能;我冒昧地在下面写了一个例子。只需将其放在文档的底部(这样当它运行时,元素已经存在),它就会找到您的autofocus
元素(注意:您应该只有一个,否则您可能会得到),并将焦点放在它上面
(function () {
// Proceed only if new inputs don't have the autofocus property
if ( document.createElement("input").autofocus === undefined ) {
// Get a reference to all forms, and an index variable
var forms = document.forms, fIndex = -1;
// Begin cycling over all forms in the document
formloop: while ( ++fIndex < forms.length ) {
// Get a reference to all elements in form, and an index variable
var elements = forms[ fIndex ].elements, eIndex = -1;
// Begin cycling over all elements in collection
while ( ++eIndex < elements.length ) {
// Check for the autofocus attribute
if ( elements[ eIndex ].attributes["autofocus"] ) {
// If found, trigger focus
elements[ eIndex ].focus();
// Break out of outer loop
break formloop;
}
}
}
}
}());
(函数(){
//仅当新输入没有自动聚焦属性时才继续
if(document.createElement(“输入”).autofocus==未定义){
//获取对所有窗体的引用和索引变量
var forms=document.forms,fIndex=-1;
//开始循环浏览文档中的所有表单
formloop:while(++fIndex
经过一些初步测试后,它似乎提供了对InternetExplorer6、Firefox3等的支持
在您选择的浏览器中测试:乔纳森·桑普森的HTML5解决方案可能是最好的。如果使用jQuery,steo的示例也应该可以使用。完整地说,这里是针对所有浏览器和IE10的简单JS解决方案+
window.addEventListener("load",function() {
document.getElementById("namanyay-search-box").focus();
});
window.addEventListener("load",function() {
document.getElementById("namanyay-search-box").focus();
});