專案裡到處都是 alert 和確認視窗,看久了實在不好看。後來把其中幾個改成「遮罩層 + 置中浮層」的形式,整個介面立刻高檔起來。做法不難,但細節比想像中多:遮罩要蓋滿整頁、浮層要置中、捲動時還要跟著跑、關閉時要記得把事件解掉。
浮層的內容來自另一個 jsp,先包在一個隱藏的 div 裡。這裡有個坑:用 jsp:include 會報錯,改用 include file 就正常,推測和載入順序有關(尚未深入研究)。
<div id='newDiv1' style="display: none;"> <%@ include file="/WEB-INF/jsp/infobackup/martyr/printCertDia.jsp" %> </div>
另外提醒一個很常踩的雷:標籤的 name 和 id 取一樣的名字時,JavaScript 取值會出錯,要避免。
關鍵是建立一個跟 body 一樣大的 div,把整頁蓋住。zIndex 決定層級,filter 與 opacity 決定透明度。
// mask 遮罩層
var newMask = document.createElement("div");
newMask.id = m;
newMask.style.position = "absolute";
newMask.style.zIndex = "1";
_scrollWidth = Math.max(document.body.scrollWidth, document.documentElement.scrollWidth);
_scrollHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
newMask.style.width = _scrollWidth + "px";
newMask.style.height = _scrollHeight + "px";
newMask.style.top = "0px";
newMask.style.left = "0px";
newMask.style.background = "#666";
newMask.style.filter = "alpha(opacity=40)"; // 舊 IE
newMask.style.opacity = "0.40"; // 標準瀏覽器
document.body.appendChild(newMask);
newDiv = document.getElementById("newDiv1");
newDiv.style.position = "absolute";
newDiv.style.zIndex = "9999"; // 一定高於遮罩
newDivWidth = 700;
newDivHeight = 600;
newDiv.style.width = newDivWidth + "px";
newDiv.style.height = newDivHeight + "px";
newDiv.style.top = (document.body.scrollTop + document.body.clientHeight / 2 - newDivHeight / 2) + "px";
newDiv.style.left = (document.body.scrollLeft + document.body.clientWidth / 2 - newDivWidth / 2) + "px";
newDiv.style.background = "#F7F7EF";
newDiv.style.border = "1px solid #860001";
newDiv.style.padding = "5px";
newDiv.style.display = '';
置中的公式是:捲動量 + 視窗可視尺寸的一半 − 浮層尺寸的一半。少了 scrollTop 這一項,浮層就會釘在頁面最上方而不是使用者眼前。
function newDivCenter() {
newDiv.style.top = (document.body.scrollTop + document.body.clientHeight / 2 - newDivHeight / 2) + "px";
newDiv.style.left = (document.body.scrollLeft + document.body.clientWidth / 2 - newDivWidth / 2) + "px";
}
if (document.all) {
window.attachEvent("onscroll", newDivCenter);
} else {
window.addEventListener('scroll', newDivCenter, false);
}
關閉時要做四件事:解除捲動監聽、移除浮層、移除遮罩、還原被藏起來的元素。少了第一步,關掉之後捲動仍然會觸發一個已經不存在的元素,瀏覽器就開始抱怨了。
var newA = document.createElement("a");
newA.href = "#";
newA.innerHTML = "關閉";
newA.onclick = function () {
if (document.all) {
window.detachEvent("onscroll", newDivCenter);
} else {
window.removeEventListener('scroll', newDivCenter, false);
}
document.body.removeChild(document.getElementById("newDiv1"));
document.body.removeChild(document.getElementById(m));
document.getElementById("certImg").style.display = '';
return false;
};
newDiv.appendChild(newA);
這套手寫邏輯是理解遮罩層原理的好教材,但新專案沒必要重造。同等效果用一個 fixed 定位的容器加 opacity 就能少掉 scroll 監聽那一段;再搭配 focus trap 與 Esc 關閉,才是完整的 Modal。若團隊已有前端框架,直接用現成元件會省下很多邊界處理。