模態彈窗的背景遮罩(置灰)是標準交互:視覺聚焦、阻斷底層交互、層級管理。本文實現一個輕量級 Dialog 類,模擬 EasyUI Dialog 風格,純原生 JS、無依賴、支援多實例、拖拽、動畫。
var Dialog = (function() {
var zIndexBase = 9999;
var instances = [];
function Dialog(options) {
this.options = Object.assign({
id: 'dialog_' + Date.now(),
title: '',
content: '',
width: 400,
height: 300,
draggable: true,
modal: true,
onClose: null
}, options);
this.mask = null;
this.dialog = null;
this.init();
}
Dialog.prototype.init = function() {
this.createMask();
this.createDialog();
this.bindEvents();
this.show();
};
Dialog.prototype.createMask = function() {
if (!this.options.modal) return;
this.mask = document.createElement('div');
this.mask.className = 'dialog-mask';
this.mask.style.cssText =
'position:fixed;top:0;left:0;width:100%;height:100%;' +
'background:#000;opacity:0.3;filter:alpha(opacity=30);' +
'z-index:' + (zIndexBase++) + ';display:none;';
document.body.appendChild(this.mask);
};
Dialog.prototype.createDialog = function() {
this.dialog = document.createElement('div');
this.dialog.id = this.options.id;
this.dialog.className = 'dialog-window';
this.dialog.style.cssText =
'position:fixed;z-index:' + (zIndexBase++) + ';' +
'width:' + this.options.width + 'px;height:' + this.options.height + 'px;' +
'background:#fff;border:1px solid #ccc;box-shadow:0 4px 12px rgba(0,0,0,.2);' +
'display:none;overflow:hidden;';
// 標題欄
var header = document.createElement('div');
header.className = 'dialog-header';
header.style.cssText = 'padding:10px 15px;background:#fafafa;border-bottom:1px solid #eee;cursor:move;';
header.innerHTML = '' + this.options.title + '' +
'';
this.dialog.appendChild(header);
// 內容區
var body = document.createElement('div');
body.className = 'dialog-body';
body.style.cssText = 'padding:15px;height:calc(100% - 42px);overflow:auto;';
body.innerHTML = this.options.content;
this.dialog.appendChild(body);
document.body.appendChild(this.dialog);
this.center();
};
Dialog.prototype.bindEvents = function() {
var self = this;
// 關閉按鈕
this.dialog.querySelector('.dialog-close').onclick = function() { self.close(); };
// 遮罩點擊關閉
if (this.mask) {
this.mask.onclick = function() { self.close(); };
}
// 拖拽
if (this.options.draggable) {
var header = this.dialog.querySelector('.dialog-header');
var dragging = false, startX, startY, startLeft, startTop;
header.onmousedown = function(e) {
e = e || window.event;
dragging = true;
startX = e.clientX;
startY = e.clientY;
startLeft = self.dialog.offsetLeft;
startTop = self.dialog.offsetTop;
header.style.cursor = 'grabbing';
document.onmousemove = dragMove;
document.onmouseup = dragEnd;
e.preventDefault();
};
function dragMove(e) {
if (!dragging) return;
e = e || window.event;
var left = startLeft + (e.clientX - startX);
var top = startTop + (e.clientY - startY);
// 邊界約束
left = Math.max(0, Math.min(left, window.innerWidth - self.dialog.offsetWidth));
top = Math.max(0, Math.min(top, window.innerHeight - self.dialog.offsetHeight));
self.dialog.style.left = left + 'px';
self.dialog.style.top = top + 'px';
}
function dragEnd() {
dragging = false;
header.style.cursor = 'move';
document.onmousemove = document.onmouseup = null;
}
}
// ESC 關閉
document.onkeydown = function(e) {
if (e.key === 'Escape' && self.isOpen()) self.close();
};
// 窗口縮放居中
window.onresize = function() { if (self.isOpen()) self.center(); };
};
Dialog.prototype.center = function() {
var w = this.dialog.offsetWidth;
var h = this.dialog.offsetHeight;
this.dialog.style.left = (window.innerWidth - w) / 2 + 'px';
this.dialog.style.top = (window.innerHeight - h) / 2 + 'px';
};
Dialog.prototype.show = function() {
if (this.mask) this.mask.style.display = 'block';
this.dialog.style.display = 'block';
// 簡單動畫
this.dialog.style.opacity = '0';
this.dialog.style.transform = 'scale(0.95)';
var self = this;
requestAnimationFrame(function() {
self.dialog.style.transition = 'opacity 0.2s, transform 0.2s';
self.dialog.style.opacity = '1';
self.dialog.style.transform = 'scale(1)';
});
};
Dialog.prototype.close = function() {
var self = this;
this.dialog.style.opacity = '0';
this.dialog.style.transform = 'scale(0.95)';
setTimeout(function() {
if (self.mask) { self.mask.remove(); self.mask = null; }
self.dialog.remove();
instances.splice(instances.indexOf(self), 1);
if (self.options.onClose) self.options.onClose();
}, 200);
};
Dialog.prototype.isOpen = function() {
return this.dialog && this.dialog.parentNode === document.body;
};
return Dialog;
})();
// 使用示例
new Dialog({
title: '用戶信息',
content: '<form><input placeholder="姓名"><input placeholder="郵箱"></form>',
width: 500,
height: 350,
onClose: function() { console.log('對話框已關閉'); }
});
<style>
.dialog-mask { position:fixed; inset:0; background:#000; opacity:.3; z-index:9998; }
.dialog-window { position:fixed; z-index:9999; background:#fff; border:1px solid #ddd; box-shadow:0 8px 24px rgba(0,0,0,.2); border-radius:4px; overflow:hidden; }
.dialog-header { display:flex; justify-content:space-between; align-items:center; padding:0 15px; height:42px; background:#fafafa; border-bottom:1px solid #eee; cursor:move; }
.dialog-title { font-weight:500; }
.dialog-close { background:none; border:none; font-size:20px; line-height:1; color:#999; cursor:pointer; padding:0 5px; }
.dialog-close:hover { color:#333; }
.dialog-body { padding:15px; overflow:auto; }
</style>
zIndexBase 遞增,保證多彈窗正確疊加。instances 數組跟蹤所有打開的彈窗,支援 closeAll。transition + requestAnimationFrame 觸發,避免初始狀態直接生效。close() 中 remove() DOM、清理事件引用、從實例數組移除。window.onresize 應加防抖。手寫 Dialog 類能深入理解模態框核心機制:遮罩層、層級、定位、拖拽、生命週期。生產項目建議:簡單場景用 <dialog> 原生元素;複雜業務用組件庫(Element Plus Dialog、Ant Design Modal、Bootstrap Modal),獲得無障礙、焦點陷阱、服務端渲染、TypeScript 類型支援等企業級特性。