html5中的autofocus(自動聚焦)屬性介紹

字號:


    這里要講的一個簡單的html5功能是當頁面加載完成時讓輸入焦點自動落到某個元素上;這個動作用autofocus屬性完成。
    html代碼非常簡單:
    代碼如下:
    <!-- these all work! -->
    <input autofocus=autofocus />
    <button autofocus=autofocus>hi!</button>
    <textarea autofocus=autofocus></textarea>
    當有了autofocus屬性,這些 input, textarea, 或 button元素都能在頁面加載是被選中。但如果使用純顯示元素,例如h1標記,autofocus屬性并不好用。
    這個屬性在某些情況下非常有用。例如谷歌的首頁,人們99%的時間都是用它來搜索,所以頁面一旦加載,光標必然定位在輸入框里。以前需要使用javascript才能完成,現(xiàn)在完全不需要了,html自己就能完成。