为您的文本输入提供autofocus
属性。它有相当好的浏览器支持,虽然并不完美。我们可以很容易地填充这个功能;我冒昧地在下面写了一个例子。只需将它放在文档的底部(这样当它运行时,元素已经存在),它会找到你的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;
}
}
}
}
}());
经过一些初步测试,这似乎一直支持 Internet Explorer 6、Firefox 3 等。
在您选择的浏览器中进行测试:http: //jsfiddle.net/jonathansampson/qZHxv/show