彈出層(modal)的視覺結構通常拆成三層:最底下一層半透明遮罩負責「隔離」背景,中間一層深色邊框製造立體感,最上面才是承載內容的白色容器。把這三層的職責分開,樣式會好維護很多。
.alertMessageBg { /* 遮罩層 */
position: fixed;
_position: absolute; /* IE6 hack */
width: 100%; height: 100%;
left: 0; top: 0;
background: #000;
opacity: 0.5;
-moz-opacity: 0.5;
filter: alpha(opacity=50);
z-index: 97;
display: none;
}
.alertMessageDivBorder { /* 邊框層 */
position: fixed;
_position: absolute;
width: 750px; height: 370px;
left: 50%; top: 50%;
margin: -185px 0 0 -375px; /* 負 margin 置中 */
background: #000;
opacity: 0.3;
z-index: 98;
display: none;
}
.alertMessageDiv { /* 內容層 */
position: fixed;
_position: absolute;
width: 730px; height: 350px;
left: 50%; top: 50%;
margin: -175px 0 0 -365px;
background: #fff;
z-index: 99;
display: none;
font-size: 14px;
}
<div class="alertMessageBg"></div> <div class="alertMessageDivBorder"></div> <div class="alertMessageDiv"></div>
直接給 position: fixed 搭配 width/height: 100%,瀏覽器會自動讓它貼合視窗,不需要一行 JavaScript。
如果必須相容 IE6(fixed 在 IE6 失效),就得手動抓 body 尺寸:
var bgWidth = document.body.clientWidth + 'px',
bgHeight = document.body.clientHeight + 'px',
alertBgNode = $('.alertMessageBg');
alertBgNode.css({ 'width': bgWidth, 'height': bgHeight });
兩者相較,純 CSS 方案明顯更省事,在已經不必理會 IE6 的今天,沒有理由再走 JS 量測這條路。
body 加上 overflow: hidden,否則滾輪會把底下的頁面滾動起來,體驗很差。display:flex; align-items:center; justify-content:center)可以彻底擺脫這個問題。role="dialog"、aria-modal="true",並在開啟時把焦點移入、關閉時還原,同時讓 Tab 焦點留在彈窗內,鍵盤與螢幕閱讀器使用者才能正常操作。