模態彈窗是高頻組件,但無障礙實現常被忽視。本文構建一個生產級 Modal 類別:Focus Trap 循環焦點、ESC 關閉、點擊遮罩關閉、背景滾動鎖定、動畫過渡、多實例管理、無障礙屬性完整。
<button data-modal-trigger="demo">打開彈窗</button>
<div class="modal" id="demo" role="dialog" aria-modal="true" aria-labelledby="demo-title" hidden>
<div class="modal-overlay" data-modal-close></div>
<div class="modal-content">
<header>
<h2 id="demo-title">標題</h2>
<button class="modal-close" data-modal-close aria-label="關閉">×</button>
</header>
<div class="modal-body">內容區域</div>
</div>
</div>
.modal { position: fixed; inset: 0; z-index: 1000; display: flex; align-items: center; justify-content: center; }
.modal[hidden] { display: none; }
.modal-overlay { position: absolute; inset: 0; background: rgba(0,0,0,0.5); }
.modal-content { position: relative; width: 90%; max-width: 500px; background: #fff; border-radius: 8px; overflow: hidden; transform: scale(0.95); opacity: 0; transition: 0.2s; }
.modal:not([hidden]) .modal-content { transform: scale(1); opacity: 1; }
/* 背景滾動鎖定 */
body.modal-open { overflow: hidden; padding-right: 17px; /* 補償滾動條寬度 */ }
class Modal {
constructor(modalEl) {
this.modal = modalEl;
this.triggers = document.querySelectorAll(`[data-modal-trigger="${modalEl.id}"]`);
this.closeBtns = modalEl.querySelectorAll('[data-modal-close]');
this._lastFocused = null;
this._focusableSelector = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
this._bind();
}
_bind() {
this.triggers.forEach(btn => btn.addEventListener('click', () => this.open()));
this.closeBtns.forEach(btn => btn.addEventListener('click', () => this.close()));
this.modal.addEventListener('keydown', this._onKeyDown.bind(this));
}
open() {
this._lastFocused = document.activeElement;
document.body.classList.add('modal-open');
this.modal.hidden = false;
// 等待下一幀確保顯示後再聚焦
requestAnimationFrame(() => this._trapFocus(true));
}
close() {
this.modal.hidden = true;
document.body.classList.remove('modal-open');
this._lastFocused?.focus(); // 歸還焦點
}
_onKeyDown(e) {
if (e.key === 'Escape') this.close();
if (e.key === 'Tab') this._trapFocus(false);
}
_trapFocus(init) {
const focusable = this.modal.querySelectorAll(this._focusableSelector);
if (!focusable.length) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (init) { first.focus(); return; }
if (document.activeElement === last && !e.shiftKey) { e.preventDefault(); first.focus(); }
else if (document.activeElement === first && e.shiftKey) { e.preventDefault(); last.focus(); }
}
}
// 初始化所有模態框
document.querySelectorAll('.modal[role="dialog"]').forEach(el => new Modal(el));
.modal-body 設定 max-height: 70vh; overflow: auto;。modal.close()。