2013-04-13 28 views
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"/> 

回答

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

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

或者你也可以試試$(window).load()

3

給你的文字輸入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

+0

當輸入不是在表單中工作嗎? – ViniciusPires

2

喬納森·桑普森的HTML5解決方案可能是最好的。如果您使用jQuery,那麼steo的示例也應該可以工作。要完成,在這裏你去所有瀏覽器和IE10普通JS解決方案+

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