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

字號(hào):


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