HTML 的 tabindex 屬性開發過程當中通常不會使用到,最近開發中有個需求兼顧富交互,便總結了一下。本篇文章同時收錄在個人【前端知識點】中,Github連接直達,歡迎 Starhtml
按照慣例,放上官方定義前端
兼容性:Safari不支持!git
在咱們平常使用網頁的過程當中,能夠經過鍵盤控制一些元素的聚焦,從而達到便捷訪問的目的github
element
分爲 focusable
和 非focusable
,若是使用了tabindex就能夠改變相關的行爲面試
在HTML中有6個元素默認支持聚焦:編程
href
屬性的 <a>
標籤href
屬性的 <link>
標籤<button></button>
標籤<input />
標籤 (排除帶有 type="hidden"
屬性的)<select></select>
標籤<textarea></textarea>
標籤以上的元素默認均可以使用 Tab
鍵,以及 JS focus()
方法聚焦緩存
document.querySelector("a").focus();
tab鍵
進行聚焦元素時,聚焦的順序等於元素在代碼中的出現前後順序,當咱們進行富交互優化時,就須要用到 tabindex
這個屬性來幫助咱們進行更好用戶體驗的優化了①元素是否能聚焦:經過鍵盤這類輸入設備,或者經過 JS focus()
方法性能優化
②元素何時能聚焦:在用戶經過鍵盤與頁面交互時微信
通俗來講:就是當用戶使用鍵盤時,tabindex用來定位html元素,即便用tab鍵時焦點的順序。網絡
tabindex=0,該元素能夠用tab鍵獲取焦點
tabindex<=-1,該元素用tab鍵獲取不到焦點,可是能夠經過js獲取
-1~-999
之間沒有區別,但爲了可讀性和一致性考慮,推薦使用 -1tabindex>=1,該元素能夠用tab鍵獲取焦點,並且優先級大於tabindex=0
tabindex>=1
時,數字越小,越先定位到;// HTML <button type="button" tabindex="1">tabindex === 1</button> <button type="button" tabindex="999">tabindex === 999</button> <button type="button" tabindex="0">tabindex === 0</button>
tabindex
數值的節點,根據 DOM節點
前後順序決定聚焦順序// HTML <button type="button" tabindex="0">tabindex === 0</button> <button type="button" tabindex="1">tabindex === 1</button> <button type="button" tabindex="999">tabindex === 999</button> <button type="button" tabindex="0">tabindex === 0</button>
tabindex
設置爲 -1
時,當前節點使用 tab鍵
不能聚焦// HTML <button type="button">未設置tabindex</button> <button type="button" tabindex="-1">tabindex === -1</button> <button type="button" tabindex="0">tabindex === 0</button> <button type="button" tabindex="1">tabindex === 1</button>
tabindex
結合JS可讓默認不支持聚焦的節點進行聚焦,tabindex
爲不超出範圍的任何整數值均可以// HTML <button type="button" @click="clickBtn()">點擊讓DIV聚焦</button> <div id="FocusDiv" ref="FocusDiv" tabindex="-1">這是一個div</div> // JS clickBtn: function() { document.getElementById('FocusDiv').focus(); }
tabindex
爲它增長聚焦功能,從而能夠像不少可聚焦節點同樣進行順次焦點聚焦了toast
組件、模態框、側邊彈出信息等,咱們不但願節點被用戶聚焦捕獲,能夠將節點的 tabindex
設置爲 -1
,就能避免這一問題tabindex
值的大小來進行處理。若是你以爲這篇文章對你有益,煩請點贊以及分享給更多須要的人!
快到碗裏來!百度校招還有HC!甩簡從來!
極速直接內推【字節跳動】&【百度】&【猿輔導】&【京東】
歡迎關注微信公衆號【全棧道路】,獲取更多科技相關知識及免費書籍。