模態彈窗是 Web 應用的核心交互組件。雖然成熟庫 (Bootstrap Modal, Element Plus Dialog, Ant Design Modal) 功能強大,但理解**原生實現原理**對於定制化、效能優化、避免依賴膨脹至關重要。本文從零構建一個功能完整的 Dialog 類:遮罩層、居中定位、滾動鎖定、鍵盤無障礙、拖拽移動、動畫過渡、多實例管理。
role="dialog", aria-modal="true", aria-labelledby, focus trap/**
* 原生 JS 模態彈窗組件
* 用法:
* const dialog = new Dialog({ title: '標題', content: '<p>內容</p>' });
* dialog.show();
*/
class Dialog {
static instances = []; // 管理所有實例,處理堆疊 z-index
static zIndexBase = 1000;
constructor(options = {}) {
this.options = Object.assign({
title: '',
content: '',
width: '500px',
maxWidth: '90vw',
height: 'auto',
maxHeight: '80vh',
closable: true,
maskClosable: true,
draggable: false,
destroyOnClose: false,
onShow: null,
onHide: null,
onDestroy: null,
className: '',
footer: null // 自定義底部 HTML
}, options);
this.isOpen = false;
this.$el = null;
this.$mask = null;
this.$focusableElements = null;
this._lastFocused = null; // 記錄打開前聚焦元素
this._boundEvents = {}; // 綁定的事件引用,用於解綁
}
// ===== 核心生命週期 =====
show() {
if (this.isOpen) return this;
this._createElements();
this._bindEvents();
this._trapFocus();
this._lockScroll();
this._updateZIndex();
// 強制回流觸發動畫
this.$el.offsetHeight;
this.$el.classList.add('dialog-open');
this.$mask.classList.add('dialog-mask-open');
this.isOpen = true;
this.options.onShow && this.options.onShow(this);
Dialog.instances.push(this);
return this;
}
hide() {
if (!this.isOpen) return this;
this.$el.classList.remove('dialog-open');
this.$mask.classList.remove('dialog-mask-open');
// 等待動畫結束再移除 DOM
setTimeout(() => {
this._unbindEvents();
this._restoreFocus();
this._unlockScroll();
this.$el.remove();
this.$mask.remove();
this.$el = this.$mask = null;
this.isOpen = false;
this.options.onHide && this.options.onHide(this);
// 從實例堆疊移除
const idx = Dialog.instances.indexOf(this);
if (idx > -1) Dialog.instances.splice(idx, 1);
if (this.options.destroyOnClose) this.destroy();
}, 300); // 與 CSS transition 時間一致
return this;
}
destroy() {
this.hide();
this.options.onDestroy && this.options.onDestroy(this);
Dialog.instances = Dialog.instances.filter(i => i !== this);
}
// ===== DOM 構建 =====
_createElements() {
// 遮罩層
this.$mask = document.createElement('div');
this.$mask.className = 'dialog-mask' + (this.options.className ? ' ' + this.options.className : '');
document.body.appendChild(this.$mask);
// 彈窗主體
this.$el = document.createElement('div');
this.$el.className = 'dialog' + (this.options.className ? ' ' + this.options.className : '');
this.$el.setAttribute('role', 'dialog');
this.$el.setAttribute('aria-modal', 'true');
this.$el.style.width = this.options.width;
this.$el.style.maxWidth = this.options.maxWidth;
this.$el.style.maxHeight = this.options.maxHeight;
if (this.options.height !== 'auto') this.$el.style.height = this.options.height;
// 內部結構
let headerHtml = '';
if (this.options.title || this.options.closable) {
headerHtml = `
${this.options.title ? `${this.options.title}
` : ''}
${this.options.closable ? `` : ''}
`;
}
const footerHtml = this.options.footer
? ``
: '';
this.$el.innerHTML = `
${headerHtml}
${this.options.content}
${footerHtml}
`;
document.body.appendChild(this.$el);
// 設置 aria-labelledby
const $title = this.$el.querySelector('.dialog-title');
if ($title) this.$el.setAttribute('aria-labelledby', $title.id);
// 可拖拽
if (this.options.draggable) this._enableDrag();
}
// ===== 事件綁定 =====
_bindEvents() {
const self = this;
const { maskClosable, closable } = this.options;
// 關閉按鈕
if (closable) {
this._boundEvents.closeClick = this.hide.bind(this);
this.$el.querySelector('.dialog-close').addEventListener('click', this._boundEvents.closeClick);
}
// 點擊遮罩關閉
if (maskClosable) {
this._boundEvents.maskClick = (e) => {
if (e.target === this.$mask) this.hide();
};
this.$mask.addEventListener('click', this._boundEvents.maskClick);
}
// Esc 鍵關閉
this._boundEvents.keyDown = (e) => {
if (e.key === 'Escape') this.hide();
};
document.addEventListener('keydown', this._boundEvents.keyDown);
// 窗口 resize 重新居中 (可選,CSS 通常足夠)
// this._boundEvents.resize = () => this._center();
// window.addEventListener('resize', this._boundEvents.resize);
}
_unbindEvents() {
if (this.options.closable) {
this.$el.querySelector('.dialog-close').removeEventListener('click', this._boundEvents.closeClick);
}
if (this.options.maskClosable) {
this.$mask.removeEventListener('click', this._boundEvents.maskClick);
}
document.removeEventListener('keydown', this._boundEvents.keyDown);
// window.removeEventListener('resize', this._boundEvents.resize);
}
// ===== 無障礙:焦點陷阱 =====
_trapFocus() {
// 記錄打開前的焦點
this._lastFocused = document.activeElement;
// 獲取彈窗內可聚焦元素
this.$focusableElements = this.$el.querySelectorAll(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
const first = this.$focusableElements[0];
const last = this.$focusableElements[this.$focusableElements.length - 1];
// 聚焦首個可聚焦元素 (或關閉按鈕)
(first || this.$el.querySelector('.dialog-close') || this.$el).focus();
// Tab 循環邏輯
this._boundEvents.focusTrap = (e) => {
if (e.key !== 'Tab') return;
if (e.shiftKey) {
if (document.activeElement === first) {
e.preventDefault();
last.focus();
}
} else {
if (document.activeElement === last) {
e.preventDefault();
first.focus();
}
}
};
this.$el.addEventListener('keydown', this._boundEvents.focusTrap);
}
_restoreFocus() {
this.$el.removeEventListener('keydown', this._boundEvents.focusTrap);
if (this._lastFocused && typeof this._lastFocused.focus === 'function') {
this._lastFocused.focus();
}
}
// ===== 滾動鎖定 (含 iOS 修復) =====
_lockScroll() {
const scrollBarWidth = window.innerWidth - document.documentElement.clientWidth;
document.body.style.overflow = 'hidden';
document.body.style.paddingRight = scrollBarWidth + 'px';
// iOS Safari 修復:防止背景滾動
document.body.classList.add('dialog-open-body');
}
_unlockScroll() {
document.body.style.overflow = '';
document.body.style.paddingRight = '';
document.body.classList.remove('dialog-open-body');
}
// ===== 居中與 Z-Index 管理 =====
_center() {
// 現代瀏覽器用 CSS flex/grid 居中更好,此處保留 JS 兜底
if (this.$el) {
this.$el.style.top = '50%';
this.$el.style.left = '50%';
this.$el.style.transform = 'translate(-50%, -50%)';
}
}
_updateZIndex() {
const index = Dialog.instances.length;
this.$mask.style.zIndex = Dialog.zIndexBase + index * 2;
this.$el.style.zIndex = Dialog.zIndexBase + index * 2 + 1;
}
// ===== 可拖拽 (可選) =====
_enableDrag() {
const $header = this.$el.querySelector('.dialog-header');
if (!$header) return;
$header.style.cursor = 'move';
let startX, startY, startLeft, startTop;
const onMouseDown = (e) => {
if (e.target.closest('.dialog-close')) return; // 排除關閉按鈕
startX = e.clientX;
startY = e.clientY;
const rect = this.$el.getBoundingClientRect();
startLeft = rect.left;
startTop = rect.top;
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
};
const onMouseMove = (e) => {
const dx = e.clientX - startX;
const dy = e.clientY - startY;
this.$el.style.left = (startLeft + dx) + 'px';
this.$el.style.top = (startTop + dy) + 'px';
this.$el.style.transform = 'none'; // 禁用 transform 居中
};
const onMouseUp = () => {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
};
$header.addEventListener('mousedown', onMouseDown);
this._boundEvents.dragDown = onMouseDown; // 為了 destroy 時清理 (此處簡化)
}
}
// ===== 必須配套的 CSS (dialog.css) =====
/*
.dialog-mask {
position: fixed; top: 0; left: 0; right: 0; bottom: 0;
background: rgba(0,0,0,0.5);
opacity: 0; visibility: hidden;
transition: opacity 0.3s, visibility 0.3s;
}
.dialog-mask-open { opacity: 1; visibility: visible; }
.dialog {
position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
background: #fff; border-radius: 8px; box-shadow: 0 10px 40px rgba(0,0,0,0.2);
opacity: 0; visibility: hidden; pointer-events: none;
transition: opacity 0.3s, visibility 0.3s, transform 0.3s;
display: flex; flex-direction: column; overflow: hidden;
}
.dialog-open { opacity: 1; visibility: visible; pointer-events: auto; }
.dialog-header { display: flex; justify-content: space-between; align-items: center; padding: 16px 20px; border-bottom: 1px solid #eee; }
.dialog-title { margin: 0; font-size: 18px; font-weight: 600; }
.dialog-close { background: none; border: none; font-size: 24px; line-height: 1; cursor: pointer; color: #999; padding: 0; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; border-radius: 4px; }
.dialog-close:hover { background: #f5f5f5; color: #333; }
.dialog-body { padding: 20px; overflow: auto; flex: 1; }
.dialog-footer { padding: 12px 20px; border-top: 1px solid #eee; display: flex; justify-content: flex-end; gap: 8px; }
/* iOS 滾動鎖定修復 */
.dialog-open-body { position: fixed; width: 100%; height: 100%; overflow: hidden; }
*/
const dialog = new Dialog({
title: '確認刪除',
content: '確定要刪除此項目嗎?此操作不可恢復。
',
footer: ' '
});
dialog.show();
const formDialog = new Dialog({
title: '新增用戶',
content: `
`,
footer: '',
width: '450px',
onShow: () => {
// 表單驗證初始化等
}
});
formDialog.show();
// 全局關閉所有彈窗
Dialog.instances.slice().forEach(d => d.hide());
// 獲取當前最上層彈窗
const topDialog = Dialog.instances[Dialog.instances.length - 1];
見代碼註釋區塊,核心點:
position: fixed + transform: translate(-50%, -50%) 居中opacity/visibility 雙重控制動畫 (避免 display:none 無法動畫)z-index 由 JS 統一管理,避免衝突dialog-open-body 解決 iOS Safari 背景滾動穿透| 問題 | 解決 |
|---|---|
| 彈窗內輸入框在 iOS 無法聚焦 | 確保 dialog-open-body 不影響彈窗內部,或用 touch-action: manipulation |
| 多層彈窗遮罩穿透 | JS 管理 zIndex 堆疊,每層遮罩獨立 |
| 內容過長超出視口 | max-height: 80vh + dialog-body overflow:auto |
| 動畫結束前重複點擊導致閃爍 | isOpen 狀態鎖 + CSS pointer-events 控制 |
| 需要支援 React/Vue 內容 | 用 ReactDOM.createPortal / Teleport 將組件渲染到 .dialog-body |
一個生產級的 Dialog 組件約 300-500 行核心代碼,核心難點在於**焦點管理、滾動鎖定、動畫協調、實例堆疊、無障礙合規**。本文實現涵蓋所有關鍵點,可直接用於無框架專案、或作為理解 UI 庫內部原理的教學範例。現代框架專案建議直接使用成熟庫 (如 @headlessui/vue, radix-ui, ant-design-vue),它們已完美處理上述所有邊界情況。