<div class="trigger" data-modal-target="#popup1">觸發 1</div>
<div class="trigger" data-modal-target="#popup2">觸發 2</div>
<div id="popup1" class="modal" role="dialog" aria-modal="true" aria-labelledby="popup1-title" hidden>
<div class="modal__backdrop" data-modal-close></div>
<div class="modal__panel">
<h3 id="popup1-title">彈出層 1</h3>
<p>內容區域 111</p>
<button data-modal-close>關閉</button>
</div>
</div>
<div id="popup2" class="modal" role="dialog" aria-modal="true" aria-labelledby="popup2-title" hidden>
<div class="modal__backdrop" data-modal-close></div>
<div class="modal__panel">
<h3 id="popup2-title">彈出層 2</h3>
<p>內容區域 222</p>
<button data-modal-close>關閉</button>
</div>
</div>
.modal { position: fixed; inset: 0; z-index: 1000; display: flex; align-items: center; justify-content: center; }
.modal[hidden] { display: none; }
.modal__backdrop { position: absolute; inset: 0; background: rgba(0,0,0,.4); opacity: 0; transition: opacity .2s; }
.modal__panel { position: relative; width: 90%; max-width: 400px; background: #fff; border-radius: 8px; padding: 24px; box-shadow: 0 12px 32px rgba(0,0,0,.2); transform: scale(.85) translateY(16px); opacity: 0; transition: transform .2s cubic-bezier(.2,.8,.2,1), opacity .2s; }
.modal.is-open .modal__backdrop { opacity: 1; }
.modal.is-open .modal__panel { transform: scale(1) translateY(0); opacity: 1; }
class ModalManager {
constructor() {
this.zBase = 1000;
this.openStack = [];
this._delegateTriggers();
this._delegateKeys();
}
_delegateTriggers() {
$(document).on('click', '[data-modal-target]', e => {
const target = $(e.currentTarget).data('modal-target');
this.open(target);
});
$(document).on('click', '[data-modal-close]', e => {
const $modal = $(e.currentTarget).closest('.modal');
if ($modal.length) this.close($modal[0]);
});
}
_delegateKeys() {
$(document).on('keydown', e => {
if (e.key === 'Escape' && this.openStack.length) {
this.close(this.openStack[this.openStack.length - 1]);
}
});
}
open(selector) {
const $modal = $(selector);
if (!$modal.length || $modal.hasClass('is-open')) return;
// 焦點管理
const $focusable = $modal.find('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
const $first = $focusable.first();
const $last = $focusable.last();
// 堆疊 z-index
this.zBase += 10;
$modal.css('z-index', this.zBase).removeAttr('hidden');
// 強制重繪觸發 transition
requestAnimationFrame(() => $modal.addClass('is-open'));
// 焦點陷阱
const trapFocus = e => {
if (e.key !== 'Tab') return;
if (e.shiftKey && document.activeElement === $first[0]) { e.preventDefault(); $last.focus(); }
else if (!e.shiftKey && document.activeElement === $last[0]) { e.preventDefault(); $first.focus(); }
};
$modal.off('keydown.trap').on('keydown.trap', trapFocus);
$first.focus();
this.openStack.push($modal[0]);
$('body').css('overflow', 'hidden');
}
close(el) {
const $modal = $(el);
$modal.removeClass('is-open');
$modal.off('keydown.trap');
$modal.one('transitionend', () => {
$modal.attr('hidden', '');
this.openStack = this.openStack.filter(m => m !== el);
if (!this.openStack.length) $('body').css('overflow', '');
// 歸還焦點給觸發元素(可擴展記錄 trigger)
});
}
}
// 初始化
$(() => new ModalManager());
class Modal {
constructor(triggerSel, modalSel) {
this.trigger = document.querySelector(triggerSel);
this.modal = document.querySelector(modalSel);
this._bind();
}
_bind() {
this.trigger.addEventListener('click', () => this.open());
this.modal.querySelectorAll('[data-close]').forEach(b => b.addEventListener('click', () => this.close()));
this.modal.addEventListener('click', e => { if (e.target === this.modal) this.close(); });
document.addEventListener('keydown', e => { if (e.key === 'Escape' && this.modal.classList.contains('open')) this.close(); });
}
open() {
this.modal.hidden = false;
requestAnimationFrame(() => this.modal.classList.add('open'));
this.modal.querySelector('button, [href], input, select, textarea')?.focus();
document.body.style.overflow = 'hidden';
}
close() {
this.modal.classList.remove('open');
this.modal.addEventListener('transitionend', () => {
this.modal.hidden = true;
document.body.style.overflow = '';
this.trigger.focus();
}, { once: true });
}
}
// 多實例
new Modal('[data-modal-trigger="#popup1"]', '#popup1');
new Modal('[data-modal-trigger="#popup2"]', '#popup2');
| 項目 | 建議 |
|---|---|
| 動畫性能 | 只動 `transform`/`opacity`,啟用 GPU;避免 `top/left/width/height` 觸發重排 |
| 焦點陷阱 | Tab 循環限制在彈窗內,Shift+Tab 反向循環 |
| ARIA | `role="dialog"` `aria-modal="true"` `aria-labelledby="title-id"` |
| 減少動畫 | `@media (prefers-reduced-motion) { .modal__panel { transition: none; } }` |
| SSR 友善 | HTML 直出 `hidden`,hydration 後再綁定事件,無閃爍 |
彈出層是前端高頻元件,掌握「動畫性能、焦點管理、無障礙、多實例堆疊」四大核心,即可脫離 jQuery UI / Bootstrap Modal 等重型依賴,打造輕量、可控、可樹搖的現代化 Modal 方案。