tabIndex 值範圍:1 ~ 32767tabIndex="0":排在所有正值之後,按原始碼順序tabIndex="-1":移出 Tab 循環,但可程式化 focus() 聚焦| 值 | 行為 |
|---|---|
| 正整數 (1~32767) | 明確指定 Tab 順序,優先於 0 值元素 |
| 0 | 預設順序 (原始碼順序),在正值之後 |
| 負值 (-1) | 排除 Tab 導航,但 onfocus/onblur 仍觸發 |
| 重複值 | 視同 0 值處理 (原始碼順序) |
<form>
<input name="firstName" tabIndex="1" placeholder="名">
<input name="lastName" tabIndex="2" placeholder="姓">
<input name="email" tabIndex="3" placeholder="Email">
<button tabIndex="4">送出</button>
<a href="terms.html" tabIndex="5">條款</a>
</form>
<a href="#main" tabIndex="-1" class="skip-link">跳至主內容</a>
<div id="sidebar" tabIndex="-1">...</div>
輔助技術仍可觸達,鍵盤使用者不被干擾。
// Modal 開啟時
modal.setAttribute('tabIndex', '-1');
modal.focus(); // 程式化聚焦
// 關閉時移回觸發元素
triggerElement.focus();
:focus { outline: 2px solid #00f; })tabIndex > 0 造成順序混亂,優先調整 DOM 結構element.tabIndex // 讀寫屬性值
element.focus() // 程式化聚焦 (不受 tabIndex 限制)