原生 JS 實現彈出層(模態框)是理解組件原理的最佳途徑。本文提供無依賴的完整實現:遮罩層、居中顯示、拖拽移動、邊界約束、關閉銷毀,並解析關鍵事件流與兼容性處理。
<style>
.overlay { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:#000; opacity:0.5; z-index:9998; }
.popup { display:none; position:fixed; z-index:9999; background:#fff; border:1px solid #ccc; box-shadow:0 4px 12px rgba(0,0,0,.15); }
.popup-title { padding:10px 15px; background:#f5f5f5; border-bottom:1px solid #eee; cursor:move; user-select:none; }
.popup-content { padding:20px; }
.popup-close { position:absolute; right:10px; top:10px; background:none; border:none; font-size:18px; cursor:pointer; }
</style>
<button id="btnOpen">打開彈層</button>
<div id="overlay" class="overlay"></div>
<div id="popup" class="popup" style="width:400px;height:300px;">
<div class="popup-title" id="popupTitle">標題 <button class="popup-close">×</button></div>
<div class="popup-content">這裡是彈層內容...</div>
</div>
<script>
(function() {
var overlay = document.getElementById('overlay');
var popup = document.getElementById('popup');
var titleBar = document.getElementById('popupTitle');
var closeBtn = titleBar.querySelector('.popup-close');
var isDragging = false;
var offsetX = 0, offsetY = 0;
// 顯示彈層
function show() {
overlay.style.display = 'block';
popup.style.display = 'block';
centerPopup();
}
// 隱藏彈層
function hide() {
overlay.style.display = 'none';
popup.style.display = 'none';
// 清理拖拽事件
document.onmousemove = document.onmouseup = null;
}
// 居中定位
function centerPopup() {
var w = popup.offsetWidth;
var h = popup.offsetHeight;
popup.style.left = (window.innerWidth - w) / 2 + 'px';
popup.style.top = (window.innerHeight - h) / 2 + 'px';
}
// 拖拽邏輯
titleBar.onmousedown = function(e) {
e = e || window.event;
isDragging = true;
offsetX = e.clientX - popup.offsetLeft;
offsetY = e.clientY - popup.offsetTop;
// 設置捕獲,防止鼠標移出 titleBar 失去事件
titleBar.setCapture && titleBar.setCapture();
document.onmousemove = function(e) {
if (!isDragging) return;
e = e || window.event;
var left = e.clientX - offsetX;
var top = e.clientY - offsetY;
// 邊界約束
var maxLeft = document.documentElement.clientWidth - popup.offsetWidth;
var maxTop = document.documentElement.clientHeight - popup.offsetHeight;
left = Math.max(0, Math.min(left, maxLeft));
top = Math.max(0, Math.min(top, maxTop));
popup.style.margin = '0'; // 清除可能的 margin 干擾
popup.style.left = left + 'px';
popup.style.top = top + 'px';
};
document.onmouseup = function() {
isDragging = false;
titleBar.releaseCapture && titleBar.releaseCapture();
document.onmousemove = document.onmouseup = null;
};
return false; // 防止文字選中
};
// 綁定事件
document.getElementById('btnOpen').onclick = show;
closeBtn.onclick = hide;
overlay.onclick = hide; // 點擊遮罩關閉
// 窗口縮放時保持居中
window.onresize = centerPopup;
// ESC 鍵關閉
document.onkeydown = function(e) {
if (e.key === 'Escape' && popup.style.display === 'block') hide();
};
})();
設置鼠標捕獲,確保 mousemove/mouseup 事件持續觸發在 titleBar 上,即使鼠標移出元素邊界。現代瀏覽器事件冒泡機制已足夠,但保留兼容代碼無害。
e = e || window.event; // 兼容 IE8- event 對象掛載在 window 上
var maxLeft = document.documentElement.clientWidth - popup.offsetWidth;
var maxTop = document.documentElement.clientHeight - popup.offsetHeight;
left = Math.max(0, Math.min(left, maxLeft)); // 限制在 [0, maxLeft]
top = Math.max(0, Math.min(top, maxTop));
document.onmousemove/onmouseup。.overlay { transition: opacity 0.3s; opacity: 0; pointer-events: none; }
.overlay.show { opacity: 0.5; pointer-events: auto; }
.popup { transition: transform 0.3s, opacity 0.3s; transform: scale(0.9); opacity: 0; }
.popup.show { transform: scale(1); opacity: 1; }
var PopupManager = {
instances: {},
create: function(id, options) {
// 工廠方法創建實例,存入 instances[id]
},
closeAll: function() {
Object.values(this.instances).forEach(function(inst) { inst.hide(); });
}
};
原生 JS 彈出層核心:固定定位居中、遮罩層阻斷、mousedown/move/up 拖拽三部曲、邊界約束、事件清理。理解這些底層邏輯,有助於調試組件庫問題、實現輕量級定製需求、面試考察。生產環境優先使用 <dialog> 或成熟組件庫,享受無障礙、焦點管理、動畫、服務端渲染等開箱即用能力。