HTML 結構
<div id="container">
<!-- 頁面主要內容 -->
<button id="openModal">開啟遮罩層</button>
<!-- 遮罩層(置於 container 內或 body 直屬)-->
<div id="shade" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1000;">
<div style="position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); background:#fff; padding:20px; border-radius:8px;">
<p>這是模態內容</p>
<button id="closeModal">關閉</button>
</div>
</div>
</div>
jQuery 實作(自適應視窗大小、居中、關閉)
$(function(){
var $shade = $('#shade'), $close = $('#closeModal');
// 開啟
$('#openModal').click(function(){
resizeShade();
$shade.fadeIn(200);
});
// 關閉
$close.click(function(){
$shade.fadeOut(200);
});
// 視窗縮放重新計算(fixed 定位其實不需計算,但若用 absolute 則需)
$(window).resize(function(){
if ($shade.is(':visible')) resizeShade();
});
function resizeShade() {
// 使用 fixed 定位時,寬高 100% 即可覆蓋整視窗,無需 JS 計算
// 若堅持 absolute,需:
// $shade.width($(window).width()).height($(window).height());
}
});
純 CSS 實現(無 JS,利用 :target)
<style>
.modal { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1000; }
.modal:target { display:flex; align-items:center; justify-content:center; }
.modal-content { background:#fff; padding:20px; border-radius:8px; }
</style>
<a href="#myModal">開啟</a>
<div id="myModal" class="modal">
<div class="modal-content">
內容...
<a href="#">關閉</a>
</div>
</div>
原生 JS 版(無依賴)
document.getElementById('openModal').addEventListener('click', function(){
document.getElementById('shade').style.display = 'flex';
});
document.getElementById('closeModal').addEventListener('click', function(){
document.getElementById('shade').style.display = 'none';
});
// ESC 關閉
document.addEventListener('keydown', function(e){
if (e.key === 'Escape') document.getElementById('shade').style.display = 'none';
});
最佳實踐清單
- 使用
position: fixed + inset: 0 覆蓋全視窗,無需 JS 計算寬高。
- 內容區用 Flexbox 置中:
display:flex; align-items:center; justify-content:center;。
- 提供 ESC 鍵關閉、點擊遮罩空白處關閉(可選)。
- 無障礙:
role="dialog"、aria-modal="true"、焦點陷阱。
- 動畫:CSS
transition: opacity 0.2s 比 jQuery fadeIn/Out 更流暢。