HTML5 自動聚焦autofocus屬性

原文:https://davidwalsh.name/autofocus

翻譯:http://blog.csdn.net/renfufei/article/details/9797419

HTML5 推出了一大堆精彩的東西給我們。

過去我們要用JavaScript和Flash完成的任務,比如表單驗證,輸入框空白提示(INPUT placeholders),客戶端文件上傳下載(client side file naming),以及 音頻/視頻播放,現在都可以用基本的HTML來完成了。另一個簡單的HTML功能是現在允許我們在頁面加載完成後自動將輸入焦點定位到需要的元素,通過一個叫做 autofocus的屬性完成。
代碼就如下面一樣簡單:
    <!-- These all work! -->  
    <input autofocus="autofocus" />  
    <button autofocus="autofocus">Hi!</button>  
    <textarea autofocus="autofocus"></textarea>  
當 autofocus 屬性設置以後,input,textarea,以及button 元素在頁面加載(load)以後,會被自動選中(即獲得焦點). 我嘗試其他元素(比如h1 標籤),tabIndex=0的情況,但是autofocus屬性在這些元素上根本沒有效果。
這個屬性在主要目的是獲取用戶輸入的頁面(pages whose main purpose is collecting information)是很有用的,比如google首頁(99%的情況是用來搜索)或者在線安裝嚮導(比如WordPress's installer).而且最關鍵在於——不需要JavaScript參與

完整的頁面代碼如下:

    <!DOCTYPE HTML>  
    <html>  
     <head>  
      <title> HTML5 autofocus屬性測試 </title>  
      <meta name="Generator" content="EditPlus">  
      <meta name="Author" content="[email protected]">  
      <meta name="Description" content="original=http://davidwalsh.name/autofocus">  
     </head>  
      
     <body>  
     <!-- 原則上,以下三個元素,只能有一個設置autofocus 屬性,如果多個元素都設置,應該是最後一個元素獲取了焦點 -->  
     <!-- 
     -->  
    <div>  
        <input autofocus="autofocus" />  
        <button autofocus="autofocus">Hi!</button>  
        <textarea autofocus="autofocus"></textarea>  
    </div>  
     </body>  
    </html>  



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章