DIV CSS 佈局教程網

用 JS 實現可拖動、帶半透明遮罩的 DIV 彈出層
編輯:JavaScript綜合知識     

彈出層是網頁中非常常見的互動組件,常用於提示、表單填寫或確認操作。本文將帶大家實現一個功能完整、易於調用的彈出層:點擊按鈕後彈出一個居中的窗口,背景覆蓋半透明灰色遮罩,且窗口可以隨意拖動。

功能亮點

這個彈出層具備幾個實用特性:彈出時自動在頁面中央顯示;背景生成一層灰色半透明遮罩,突出彈窗並遮擋底層內容;標題欄可拖動,方便使用者調整窗口位置;右上角提供關閉按鈕,點擊即可關閉並移除遮罩。

核心代碼

<script>
function $(id){ return document.getElementById(id); }
function AlertMsg(title, content){
var msgw = 300, msgh = 150;
// 創建遮罩背景
var sWidth = screen.availWidth;
var sHeight = document.body.scrollHeight;
var maskObj = document.createElement("div");
maskObj.setAttribute('id','maskdiv');
maskObj.style.position = "absolute";
maskObj.style.top = "0";
maskObj.style.left = "0";
maskObj.style.background = "#777";
maskObj.style.filter = "Alpha(opacity=30);";
maskObj.style.opacity = "0.3";
maskObj.style.width = sWidth + "px";
maskObj.style.height = sHeight + "px";
maskObj.style.zIndex = "10000";
document.body.appendChild(maskObj);
// 創建彈出窗口
var msgObj = document.createElement("div");
msgObj.setAttribute("id","msgdiv");
msgObj.style.position = "absolute";
msgObj.style.top = (screen.availHeight - msgh) / 4 + "px";
msgObj.style.left = (screen.availWidth - msgw) / 2 + "px";
msgObj.style.width = msgw + "px";
msgObj.style.height = msgh + "px";
msgObj.style.background = "#FFF";
msgObj.style.border = "1px solid #000";
msgObj.style.zIndex = "10001";
// 標題欄(可拖動)
var thObj = document.createElement("div");
thObj.className = "DragAble";
thObj.style.cursor = "move";
thObj.style.background = "#369";
thObj.style.color = "#FFF";
thObj.innerHTML = "<a class='close' onclick='CloseMsg()'>關閉</a>" + title;
document.body.appendChild(msgObj);
$("msgdiv").appendChild(thObj);
}
function CloseMsg(){
document.body.removeChild($("maskdiv"));
document.body.removeChild($("msgdiv"));
}
// 拖動邏輯
var isdrag=false, y, x, oDragObj;
document.onmousedown=function(e){
var oDragHandle = e.srcElement||e.target;
while(oDragHandle.tagName!="HTML" && oDragHandle.className!="DragAble"){
oDragHandle = oDragHandle.parentElement;
}
if(oDragHandle.className=="DragAble"){
isdrag=true; oDragObj=oDragHandle.parentNode;
y=e.clientY; x=e.clientX;
}
}
document.onmousemove=function(e){
if(isdrag){
oDragObj.style.top=(parseInt(oDragObj.style.top)+e.clientY-y)+"px";
oDragObj.style.left=(parseInt(oDragObj.style.left)+e.clientX-x)+"px";
}
}
document.onmouseup=function(){ isdrag=false; }
</script>
<a href="javascript:AlertMsg('溫馨提示','')">點我試試!</a>

實現要點

彈出時先用 createElement 建立遮罩層,並透過 opacity 與 filter 兼顧不同瀏覽器的透明度設定,再建立居中的彈窗。拖動功能則透過判斷滑鼠按下時是否落在帶有 DragAble 類的標題欄上,記錄初始坐標,並在 onmousemove 中即時更新窗口位置。關閉時只需把遮罩與彈窗從 DOM 中移除即可。

希望本文所述能對大家的 JavaScript 程序設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved