<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__container">
<header class="modal__header">
<h2 id="demo-title">標題</h2>
<button class="modal__close" data-modal-close aria-label="關閉">✕</button>
</header>
<div class="modal__body">內容區域</div>
<footer class="modal__footer">
<button class="btn btn--primary" data-modal-close>確定</button>
<button class="btn btn--secondary" data-modal-close>取消</button>
</footer>
</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,.5); opacity: 0; transition: opacity .2s ease; }
.modal__container { position: relative; width: 90%; max-width: 500px; background: #fff; border-radius: 8px; box-shadow: 0 12px 32px rgba(0,0,0,.2); transform: scale(.9) translateY(20px); opacity: 0; transition: transform .2s ease, opacity .2s ease; }
.modal.is-open .modal__overlay { opacity: 1; }
.modal.is-open .modal__container { transform: scale(1) translateY(0); opacity: 1; }
class Modal {
constructor(selector) {
this.el = document.querySelector(selector);
if (!this.el) throw new Error(`Modal ${selector} not found`);
this._bindEvents();
this._focusableElements = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
this._lastFocused = null;
}
_bindEvents() {
this.el.querySelectorAll('[data-modal-close]').forEach(btn => {
btn.addEventListener('click', () => this.close());
});
document.addEventListener('keydown', e => {
if (e.key === 'Escape' && this.el.classList.contains('is-open')) this.close();
});
// 焦點陷阱
this.el.addEventListener('keydown', e => {
if (e.key !== 'Tab' || !this.el.classList.contains('is-open')) return;
const focusable = this.el.querySelectorAll(this._focusableElements);
const first = focusable[0], last = focusable[focusable.length - 1];
if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
});
}
open() {
this._lastFocused = document.activeElement;
this.el.hidden = false;
// 強制重繪觸發 transition
requestAnimationFrame(() => this.el.classList.add('is-open'));
this.el.querySelector(this._focusableElements)?.focus();
document.body.style.overflow = 'hidden'; // 防止背景滾動
}
close() {
this.el.classList.remove('is-open');
this.el.addEventListener('transitionend', () => {
this.el.hidden = true;
document.body.style.overflow = '';
this._lastFocused?.focus(); // 歸還焦點
}, { once: true });
}
}
// 使用
const modal = new Modal('#demo');
document.querySelector('[data-modal-trigger="demo"]').addEventListener('click', () => modal.open());
| 功能 | 實作要點 |
|---|---|
| 多層 Modal 堆疊 | 維護全域堆疊陣列,`z-index` 遞增,關閉時只移除頂層 |
| 表單驗證攔截關閉 | `beforeClose` 回傳 Promise,resolve 才真正關閉 |
| 動畫自定義 | 透過 CSS 變數 `--modal-duration`、 `--modal-easing` 控制 |
| Server-Side Rendering 友善 | HTML 直出 `hidden`,無閃爍,hydration 後再綁定事件 |
原生 JS + CSS Transition 即可打造高效能、無障礙、可維護的 Modal 元件。拋棄 jQuery UI、Bootstrap Modal 等重型依賴,掌握核心原理(焦點管理、動畫性能、ARIA),才能在任何框架(Vue/React/Svelte)中靈活移植或自行開發設計系統元件。