621 字
3 分鐘
HTML inert 怎麼用?暫停背景區塊的點擊與鍵盤焦點
驗證於
本文目錄
擋住滑鼠的遮罩下,原本的連結仍可能在 Tab 順序裡。若畫面上一整塊內容需要暫時停止互動,可對該區塊設定 inert。瀏覽器會讓裡面的元素無法接受使用者點擊和焦點,並從無障礙樹排除。若只是讓單一原生表單控制項暫停使用,該控制項的 disabled 更直接。WHATWG HTML 的 inert 規則
把還能操作的控制項放在 inert 外面
下面是一個暫停編輯區的範例。主區塊仍可看見,恢復按鈕放在主區塊外。開啟暫停時先把焦點移給恢復按鈕,再停用主區塊。恢復時解除 inert,才把焦點還給原來的按鈕。
<!doctype html><html lang="zh-Hant"><meta charset="utf-8"><title>暫停編輯區</title><style> main[inert] { opacity: 0.55; }</style>
<main id="editor"> <button id="pause" type="button">暫停編輯</button> <label>標題 <input id="heading" value="草稿"></label> <a href="#help">編輯說明</a></main><section id="pause-panel" hidden aria-label="編輯狀態"> <p>編輯已暫停。</p> <button id="resume" type="button">恢復編輯</button></section><p id="help">在標題欄輸入草稿標題。</p>
<script> const editor = document.querySelector('#editor'); const panel = document.querySelector('#pause-panel'); const pause = document.querySelector('#pause'); const resume = document.querySelector('#resume');
pause.addEventListener('click', () => { panel.hidden = false; resume.focus(); editor.inert = true; });
resume.addEventListener('click', () => { editor.inert = false; pause.focus(); panel.hidden = true; });</script></html>儲存為 HTML 開啟後,啟用「暫停編輯」,確認焦點移到「恢復編輯」。按 Tab 和 Shift+Tab,主區塊裡的輸入框與連結應被跳過。按下恢復按鈕後,焦點回到「暫停編輯」,下一次 Tab 應能到輸入框。
inert 設成 false,為什麼還是按不到?
HTML 的 inert 是布林屬性,標記裡只要出現即為啟用,因此 inert="false" 仍會停用區塊。用 JavaScript 設定 element.inert = false,或移除 HTML 屬性。若元素看似已解除卻仍無法聚焦,也要檢查祖先。比如把整頁包進 inert 後,在裡面插入一般浮層,浮層仍在被停用的範圍內。原生 dialog.showModal() 則會在頂層顯示模態對話框,並由瀏覽器處理文件其他部分的 inert 狀態。MDN inert 說明
對整頁模態視窗,可從原生 dialog.showModal() 起步,再獨立驗收命名、開啟與關閉焦點及鍵盤操作。若還要在關閉前檢查未儲存內容,可搭配 dialog 的 requestClose 和 cancel。本例處理的是一個可見的暫停區塊,外部的其他頁面內容仍可照常操作。
參考資料:
HTML inert 怎麼用?暫停背景區塊的點擊與鍵盤焦點
https://laplusda.com/posts/html-inert-background-focus/