點擊按鈕後,頁面中央彈出一個可拖曳、可關閉的模態視窗,同時背景變灰並禁用互動,類似 QQ 登入介面的經典效果。純 JavaScript 實作,無需依賴外部庫,適合輕量級專案快速整合。
div 覆蓋整個視窗,設定半透明黑色背景(opacity: 0.3 / filter: Alpha(Opacity=30)),z-index: 101 置於內容之上。table 結構組裝標題列、關閉鈕、內容區,支援自訂寬高、標題、訊息文字。mousedown/mousemove/mouseup,限制移動範圍於可視區域內。× 同時移除遮罩與視窗元素,恢復頁面互動。function alertWin(title, msg, w, h) {
// 建立遮罩
var bgObj = document.createElement("div");
bgObj.style.cssText = "position:absolute;left:0;top:0;width:" + iWidth + "px;height:" + Math.max(document.body.clientHeight, iHeight) + "px;filter:Alpha(Opacity=30);opacity:0.3;background:#000;z-index:101;";
document.body.appendChild(bgObj);
// 建立視窗
var msgObj = document.createElement("div");
msgObj.style.cssText = "position:absolute;top:" + (iHeight - h) / 2 + "px;left:" + (iWidth - w) / 2 + "px;width:" + w + "px;height:" + h + "px;z-index:102;";
// ... 組裝 table、標題列、關閉鈕、內容區 ...
// 拖曳邏輯
titleBar.onmousedown = function() { /* 記錄初始座標,綁定 document 移動/釋放事件 */ };
closeBtn.onclick = function() { document.body.removeChild(bgObj); document.body.removeChild(msgObj); };
}
getEvent() 統一取得事件物件,相容 IE 與 Firefox。document.documentElement.clientWidth/Height 取得視窗尺寸,支援標準模式。Math.max(document.body.clientHeight, iHeight) 確保覆蓋捲動內容。<input type="button" value="點這裡" onclick="alertWin('標題', '內容訊息', 290, 208);" />
依需求調整寬高、標題、內容即可,極易客製化。