「點一下按鈕,彈出視窗,同時背景變暗」是網頁常見的互動效果。它的核心概念是:用一個半透明的遮罩層蓋住頁面,再把內容層疊在遮罩之上。本文提供三種由簡到繁的實作方式。
用兩個 div,一個當遮罩(black_overlay),一個當內容(white_content),透過切換 display 來顯示或隱藏:
<style type="text/css">
.black_overlay {
display:none; position:absolute; top:0%; left:0%;
width:100%; height:100%; background-color:black;
z-index:1001; -moz-opacity:0.8; opacity:.80; filter:alpha(opacity=80);
}
.white_content {
display:none; position:absolute; top:25%; left:25%;
width:50%; height:50%; padding:16px;
border:3px solid orange; background-color:white;
z-index:1002; overflow:auto;
}
</style>
<a href="javascript:void(0)"
onclick="document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block'">
點擊這裡打開窗口</a>
<div id="light" class="white_content">
<a href="javascript:void(0)"
onclick="document.getElementById('light').style.display='none';
document.getElementById('fade').style.display='none'">Close</a>
<br>窗口內容
</div>
<div id="fade" class="black_overlay"></div>
把顯示邏輯抽成 hid() 與 vis() 兩個函式,用 JavaScript 動態設定寬高、位置與 z-index,讓遮罩高度對齊整個頁面:
function hid() {
var div4 = document.getElementById("div1");
div4.style.display = "block";
div4.style.width = "200px";
div4.style.height = "150px";
div4.style.zIndex = "9999";
div4.style.top = "43%";
div4.style.left = "43%";
div4.style.position = "absolute";
var div3 = document.getElementById("div2");
div3.style.display = "block";
div3.style.width = "1000px";
div3.style.zIndex = "9998";
div3.style.position = "absolute";
div3.style.height = document.body.offsetHeight;
div3.style.top = "0px";
div3.style.left = "0px";
}
function vis() {
document.getElementById("div1").style.display = "none";
document.getElementById("div2").style.display = "none";
}
最完整的版本會動態計算頁面尺寸與捲動位置,讓彈出層無論視窗大小都能置中顯示,並封裝成 openLayer / closeLayer 一組函式,同時支援多個不同的彈出內容。關鍵在於透過 getPageSize() 與 getPageScroll() 取得頁面的實際寬高與捲動量,再據此把內容層定位到畫面正中央。
三個範例的共同套路都是「遮罩層 + 內容層 + z-index 分層」。差別在於定位是否自適應。若要在正式專案中使用,建議直接採用成熟的 modal 套件(如各框架的 Dialog 元件),能省去處理跨瀏覽器置中與滾動鎖定的大量細節。