給你的文字輸入autofocus
屬性。它有相當不錯的瀏覽器支持,雖然不完美。我們可以很容易地填充這個功能;我冒昧地寫下一個例子。只需將它放在文檔的底部(以便在運行時,元素已經存在),它會找到您的autofocus
元素(注意:您應該有只有一個,否則可能得到inconsistent results),並繪製焦點之上。
(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
當輸入不是在表單中工作嗎? – ViniciusPires