遮罩層(Overlay/Mask)是網頁常見的 UI 模式,用於模態對話框、載入中提示、圖片燈箱等場景。核心需求是:半透明黑色背景覆蓋全螢幕、內容層置中顯示、阻擋底層互動。
<!-- 遮罩背景層 -->
<div id="black_overlay" class="overlay" style="display: none;"></div>
<!-- 內容載入層 -->
<div id="load_content" class="modal-content" style="display: none;">
<div class="spinner-wrapper">
<img src="images/progressBar.gif" alt="載入中" />
</div>
<div class="loading-text">資料載入中,請稍候...</div>
</div>
/* === 遮罩背景層 === */
.overlay {
position: fixed; /* 相對視窗定位 */
top: 0; left: 0;
width: 100%; height: 100%;
background-color: #000;
opacity: 0.8; /* 現代瀏覽器 */
filter: alpha(opacity=80); /* IE 8- */
z-index: 1000;
overflow: hidden;
}
/* IE6 專用 Hack:模擬 fixed 定位 */
* html .overlay {
position: absolute;
/* 使用 CSS Expression 動態計算位置(IE6-7 支援) */
left: expression(documentElement.scrollLeft);
top: expression(documentElement.scrollTop);
width: expression(documentElement.clientWidth + 'px');
height: expression(documentElement.clientHeight + 'px');
}
/* 防止 IE6 背景閃爍 */
* html {
background: url(*) fixed; /* 觸發 hasLayout */
}
* html body {
margin: 0;
height: 100%;
}
/* === 內容彈層 === */
.modal-content {
position: fixed;
top: 50%; left: 50%;
transform: translate(-50%, -50%); /* 現代置中方案 */
width: 200px;
height: 50px;
padding: 20px;
background: #fff;
border: 16px solid #fff; /* 大邊框視覺效果 */
border-bottom: none;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0,0,0,0.3);
z-index: 1002;
text-align: center;
font: bold 14px/1.5 'Microsoft JhengHei', sans-serif;
}
/* IE6-8 置中回退 */
* html .modal-content,
*+html .modal-content {
position: absolute;
top: expression((documentElement.scrollTop + documentElement.clientHeight/2) + 'px');
left: expression((documentElement.scrollLeft + documentElement.clientWidth/2) + 'px');
margin-top: -45px; /* 高度一半 + 邊框 */
margin-left: -118px; /* 寬度一半 + 邊框 */
transform: none;
}
.spinner-wrapper {
display: inline-block;
margin-bottom: 8px;
}
.loading-text {
color: #333;
}
const overlay = document.getElementById('black_overlay');
const modal = document.getElementById('load_content');
function showLoading() {
overlay.style.display = 'block';
modal.style.display = 'block';
document.body.style.overflow = 'hidden'; // 防止背景滾動
}
function hideLoading() {
overlay.style.display = 'none';
modal.style.display = 'none';
document.body.style.overflow = '';
}
// 使用範例:AJAX 請求時
fetch('/api/data')
.then(() => showLoading())
.then(response => response.json())
.then(data => { /* 處理資料 */ })
.finally(() => hideLoading());
| 瀏覽器 | 支援方式 | 備註 |
|---|---|---|
| IE 6 | CSS Expression + absolute 模擬 fixed | 需啟用 hasLayout |
| IE 7-8 | filter: alpha() + absolute 回退 | 不支援 opacity、transform |
| IE 9+ | 支援 opacity、fixed、transform(IE10+) | IE9 需 -ms-transform |
| Firefox/Chrome/Safari/Edge | 完整支援現代語法 | 建議加上 -webkit- 前綴 |
若專案不需支援 IE 11 以下,強烈建議使用原生 <dialog> 元素或成熟的模態框庫(如 Modal.js、SweetAlert2),代碼更簡潔、無障礙支援更完善。