当网页加载时,如何设置文本框为默认聚焦状态

4

当我的网页加载时,我希望一个文本框能够获得焦点。如果你打开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-search-btn" value="Search" type="submit"/>
3个回答

3
给你的文本输入添加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

2

Jonathan Sampson的HTML5解决方案可能是最好的。如果你使用jQuery,steo的示例也可以工作。为了完整起见,这里提供适用于所有浏览器和IE10+的纯JS解决方案。

window.addEventListener("load",function() {
  document.getElementById("namanyay-search-box").focus();
});

0
$(document).ready(function(){

..code.. 
$('.textbox-class-name').focus();
..code.. 
});

或者你可以尝试在 $(window).load() 上运行它


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接