<div class="modal-overlay"></div>
<div class="modal-border"></div>
<div class="modal-content"></div>
.modal-overlay {
position: fixed; /* 相對視窗定位 */
inset: 0; /* top:0; right:0; bottom:0; left:0; */
background: #000;
opacity: 0.5;
z-index: 97;
display: none;
}
.modal-border {
position: fixed;
width: 750px; height: 370px;
top: 50%; left: 50%;
transform: translate(-50%, -50%); /* 完美置中 */
background: #000;
opacity: 0.3;
z-index: 98;
display: none;
}
.modal-content {
position: fixed;
width: 730px; height: 350px;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
background: #fff;
z-index: 99;
display: none;
font-size: 14px;
}
優點:無 JS 計算、效能最佳、支援響應式、transform 置中不需知寬高。
.modal-overlay {
position: absolute; /* IE6 需 absolute + 滾動事件修正 */
left: 0; top: 0;
background: #000;
opacity: 0.5;
z-index: 97;
display: none;
}
// JS 初始化
var $overlay = $('.modal-overlay');
function resizeOverlay() {
$overlay.css({
width: document.body.clientWidth + 'px',
height: document.body.clientHeight + 'px'
});
}
$(window).on('resize scroll', resizeOverlay);
resizeOverlay();
缺點:需監聽 resize/scroll、IE6 需額外 hack、效能較差。
function openModal() {
$('.modal-overlay, .modal-border, .modal-content').fadeIn(200);
}
function closeModal() {
$('.modal-overlay, .modal-border, .modal-content').fadeOut(200);
}
// ESC 鍵關閉
$(document).on('keydown', function(e) {
if (e.key === 'Escape') closeModal();
});
// 點擊遮罩關閉
$('.modal-overlay').on('click', closeModal);
role="dialog"、aria-modal="true"、aria-labelledby。原生 <dialog> 元素(Chrome 37+、Firefox 53+、Safari 15.4+):
<dialog id="modal">
<form method="dialog">
<button value="cancel">取消</button>
<button value="confirm">確認</button>
</form>
</dialog>
<script>
const d = document.getElementById('modal');
d.showModal(); // 顯示為 modal
d.close('confirm'); // 關閉並回傳值
</script>