如今要做出彈出層,各種插件垂手可得;但有時候我們就是想要一份乾淨、不依賴外部庫的原生寫法。以下示範一個具備「置中顯示、背景遮罩、可拖曳」的完整彈出層。
function showDiv() {
var Idiv = document.getElementById("Idiv");
var mou_head = document.getElementById('mou_head');
Idiv.style.display = "block";
// 讓彈出層置中顯示
Idiv.style.left = (document.documentElement.clientWidth - Idiv.clientWidth) / 2 + document.documentElement.scrollLeft + "px";
Idiv.style.top = (document.documentElement.clientHeight - Idiv.clientHeight) / 2 + document.documentElement.scrollTop - 50 + "px";
// 建立半透明遮罩,讓背景不可點擊
var procbg = document.createElement("div");
procbg.setAttribute("id", "mybg");
procbg.style.background = "#000000";
procbg.style.width = "100%";
procbg.style.height = "100%";
procbg.style.position = "fixed";
procbg.style.top = "0";
procbg.style.left = "0";
procbg.style.zIndex = "500";
procbg.style.opacity = "0.6";
procbg.style.filter = "Alpha(opacity=70)";
document.body.appendChild(procbg);
document.body.style.overflow = "hidden"; // 取消捲軸
// 拖曳效果
var posX, posY;
mou_head.onmousedown = function (e) {
if (!e) e = window.event;
posX = e.clientX - parseInt(Idiv.style.left);
posY = e.clientY - parseInt(Idiv.style.top);
document.onmousemove = mousemove;
};
document.onmouseup = function () {
document.onmousemove = null;
};
function mousemove(ev) {
if (ev == null) ev = window.event;
Idiv.style.left = (ev.clientX - posX) + "px";
Idiv.style.top = (ev.clientY - posY) + "px";
}
}
function closeDiv() {
var Idiv = document.getElementById("Idiv");
Idiv.style.display = "none";
document.body.style.overflow = "auto"; // 恢復捲軸
var mybg = document.getElementById("mybg");
document.getElementsByTagName("body")[0].removeChild(mybg);
}
<div id="Idiv" style="display:none; position:absolute; z-index:1000; background:#67a3d9;">
<div id="mou_head" style="width:100px; height:10px; z-index:1001; position:absolute;">這個是用來實現拖層</div>
<input type="button" value="關閉" onclick="closeDiv();" />
</div>
這個範例的關鍵在於三點:透過視窗寬高減去元素寬高來計算置中座標、用一個全螢幕半透明 div 當遮罩並鎖住捲軸、以及在標題區綁定 mousedown/mousemove/mouseup 事件來實現拖曳。至於圓角、陰影等美化效果,就看你如何 further 妝點了。