點擊觸發按鈕,彈出半透明遮罩層與居中彈窗,彈窗標題欄可拖拽移動,點擊關閉按鈕或遮罩層關閉。支援多實例、ES6 模組化、移動端觸控。
<button type="button" class="trigger-btn" data-dialog="demo">打開彈窗</button>
<div class="dialog-overlay" id="overlay-demo" role="dialog" aria-modal="true" aria-labelledby="title-demo" hidden>
<div class="dialog">
<header class="dialog-header">
<h3 id="title-demo">提示標題</h3>
<button type="button" class="dialog-close" aria-label="關閉">×</button>
</header>
<div class="dialog-body">這裡是彈窗內容,可以放置表單、文字、圖片等。</div>
<footer class="dialog-footer">
<button type="button" class="btn btn-secondary dialog-close">取消</button>
<button type="button" class="btn btn-primary">確定</button>
</footer>
</div>
</div>
.dialog-overlay {
position: fixed; inset: 0; background: rgba(0,0,0,.5);
display: flex; align-items: center; justify-content: center;
z-index: 1000; opacity: 0; visibility: hidden;
transition: opacity 0.2s, visibility 0.2s;
}
.dialog-overlay:not([hidden]) { opacity: 1; visibility: visible; }
.dialog {
background: #fff; border-radius: 8px; box-shadow: 0 10px 30px rgba(0,0,0,.2);
width: 90%; max-width: 480px; max-height: 90vh; overflow: auto;
transform: scale(0.9); transition: transform 0.2s;
}
.dialog-overlay:not([hidden]) .dialog { transform: scale(1); }
.dialog-header {
display: flex; align-items: center; justify-content: space-between;
padding: 16px 20px; border-bottom: 1px solid #eee;
cursor: move; /* 拖拽手柄區域 */
user-select: none;
}
.dialog-close { background: none; border: none; font-size: 24px; line-height: 1; cursor: pointer; color: #999; }
.dialog-close:hover { color: #333; }
.dialog-body { padding: 20px; }
.dialog-footer { display: flex; justify-content: flex-end; gap: 12px; padding: 16px 20px; border-top: 1px solid #eee; }
class DraggableDialog {
constructor(overlayEl) {
this.overlay = overlayEl;
this.dialog = overlayEl.querySelector('.dialog');
this.header = overlayEl.querySelector('.dialog-header');
this.closeBtns = overlayEl.querySelectorAll('.dialog-close');
this.triggerBtn = document.querySelector(`[data-dialog="${overlayEl.id.replace('overlay-', '')}"]`);
this._dragData = null;
this._boundHandlers = {
move: this._onMove.bind(this),
up: this._onUp.bind(this),
keydown: this._onKeyDown.bind(this)
};
this._initEvents();
}
_initEvents() {
// 打開觸發
this.triggerBtn?.addEventListener('click', () => this.open());
// 關閉
this.closeBtns.forEach(btn => btn.addEventListener('click', () => this.close()));
this.overlay.addEventListener('click', (e) => {
if (e.target === this.overlay) this.close(); // 僅點擊遮罩關閉
});
// 拖拽:滑鼠
this.header.addEventListener('mousedown', this._onDown.bind(this));
// 拖拽:觸控
this.header.addEventListener('touchstart', this._onDown.bind(this), { passive: false });
}
_onDown(e) {
if (e.target.closest('button')) return; // 點擊按鈕不拖拽
e.preventDefault();
const clientX = e.clientX || e.touches?.[0].clientX;
const clientY = e.clientY || e.touches?.[0].clientY;
const rect = this.dialog.getBoundingClientRect();
this._dragData = {
startX: clientX, startY: clientY,
offsetX: rect.left, offsetY: rect.top
};
document.addEventListener('mousemove', this._boundHandlers.move);
document.addEventListener('mouseup', this._boundHandlers.up);
document.addEventListener('touchmove', this._boundHandlers.move, { passive: false });
document.addEventListener('touchend', this._boundHandlers.up);
document.addEventListener('keydown', this._boundHandlers.keydown);
this.dialog.style.transition = 'none'; // 拖拽時禁用動畫
}
_onMove(e) {
if (!this._dragData) return;
const clientX = e.clientX || e.touches?.[0].clientX;
const clientY = e.clientY || e.touches?.[0].clientY;
const dx = clientX - this._dragData.startX;
const dy = clientY - this._dragData.startY;
let left = this._dragData.offsetX + dx;
let top = this._dragData.offsetY + dy;
// 邊界限制:保持在視口內
const maxLeft = window.innerWidth - this.dialog.offsetWidth;
const maxTop = window.innerHeight - this.dialog.offsetHeight;
left = Math.max(0, Math.min(left, maxLeft));
top = Math.max(0, Math.min(top, maxTop));
this.dialog.style.left = left + 'px';
this.dialog.style.top = top + 'px';
this.dialog.style.margin = 0; // 覆蓋置中 margin
}
_onUp() {
if (!this._dragData) return;
this._dragData = null;
document.removeEventListener('mousemove', this._boundHandlers.move);
document.removeEventListener('mouseup', this._boundHandlers.up);
document.removeEventListener('touchmove', this._boundHandlers.move);
document.removeEventListener('touchend', this._boundHandlers.up);
document.removeEventListener('keydown', this._boundHandlers.keydown);
this.dialog.style.transition = ''; // 恢復動畫
}
_onKeyDown(e) {
if (e.key === 'Escape') this.close();
// Tab 循環焦點限制在彈窗內(簡易版)
}
open() {
this.overlay.hidden = false;
// 重置位置至置中
this.dialog.style.left = '';
this.dialog.style.top = '';
this.dialog.style.margin = '';
this.header.focus(); // 焦點移至標題
document.body.style.overflow = 'hidden'; // 防止背景滾動
}
close() {
this.overlay.hidden = true;
document.body.style.overflow = '';
}
destroy() {
this.close();
this.header.removeEventListener('mousedown', this._onDown.bind(this));
this.header.removeEventListener('touchstart', this._onDown.bind(this));
this.triggerBtn?.removeEventListener('click', () => this.open());
}
}
// 自動初始化所有 .dialog-overlay
document.querySelectorAll('.dialog-overlay').forEach(el => new DraggableDialog(el));