試著拔掉滑鼠,只用 Tab 鍵操作自己的網站。很多問題會立刻浮現:看不到焦點在哪、按鈕按不下去、開了對話框焦點卻還留在背景。
不要移除焦點樣式
/* 不要這樣做 */
*:focus { outline: none; }
改用 :focus-visible:滑鼠點擊時不顯示,鍵盤操作時才顯示。
:focus-visible {
outline: 2px solid #005A9C;
outline-offset: 2px;
}
焦點框與背景的對比至少要 3:1。
用對元素
<!-- 不好:div 無法用鍵盤聚焦,也不會被讀成按鈕 -->
<div class="btn" onclick="save()">儲存</div>
<!-- 好 -->
<button type="button" onclick="save()">儲存</button>
原生的 <button> 自動支援 Tab 聚焦、Enter 與空白鍵觸發、螢幕閱讀器朗讀角色。用 <div> 模擬的話,這些全部要自己補。
| 需求 | 用這個 |
|---|---|
| 執行動作 | <button> |
| 前往其他頁面 | <a href> |
| 切換開關 | <button aria-pressed> 或 <input type="checkbox"> |
| 展開收合 | <details> 或 <button aria-expanded> |
開關對話框的焦點
- 開啟時,焦點移到對話框內第一個可操作元素。
- 開啟期間,Tab 鍵不能跑到背景內容。
- 關閉時,焦點回到原本觸發的按鈕。
原生 <dialog> 搭配 showModal() 會自動處理第二點。第三點仍需要自己記錄:
let lastFocus;
openBtn.addEventListener('click', () => {
lastFocus = document.activeElement;
dialog.showModal();
});
dialog.addEventListener('close', () => lastFocus?.focus());
動態內容要通知
畫面上的訊息更新了,螢幕閱讀器使用者不一定知道:
<p class="status" role="status" aria-live="polite"></p>
status.textContent = '已複製連結';
IMPORTANT
aria-live 的容器要一開始就存在於頁面中,之後只更新文字內容。動態插入整個容器的話,很多螢幕閱讀器不會朗讀。
跳到主要內容
<a class="skip-link" href="#main">跳到主要內容</a>
讓鍵盤使用者不必每頁都按十幾次 Tab 才能越過導覽列。
發表留言