DIV CSS 佈局教程網

純 CSS + JS 讓彈出對話框永遠居中並自帶遮罩
編輯:關於JavaScript     

自製對話框最難的往往不是外觀,而是「怎麼讓它永遠在畫面正中央」。單純用 margin:auto 只能水平居中,垂直方向得靠定位與位移的組合。下面這份範例連遮罩層一起做完。

結構與樣式

<!DOCTYPE html>
<html lang="zh-Hant" xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>置中對話框</title>
<style type="text/css">
/* 遮罩層:鋪滿整個視窗,半透明,墊在對話框下方 */
.Div_Scroll {
    position: fixed;
    margin: -10px;
    visibility: hidden;
    background-color: #808080;
    opacity: 0.6;
    z-index: 99;
}
/* 內容層:用 margin-top 百分比把對話框推到垂直中段 */
.Div_Scroll_Content {
    position: relative;
    margin-top: 20%;
    width: inherit;
    height: inherit;
}
/* 對話框本體:水平居中靠 margin:auto */
.Div_AlertWindow {
    margin: auto;
    width: 200px;
    height: 100px;
    background-color: lightblue;
    border: 5px solid #f00;
}
</style>

<script type="text/javascript">
var $ = function (id) { return document.getElementById(id); };

window.onload = function () {
    var alertWindow = $("alertParent");
    alertWindow.style.width  = window.screen.availWidth + "px";
    alertWindow.style.height = window.screen.height + "px";
    $("Sure").onclick = function () {
        alertWindow.style.visibility = "hidden";
    };
};

function ShowAlert() {
    $("alertParent").style.visibility = "visible";
}
</script>
</head>
<body>
<div id="alertParent" class="Div_Scroll">
  <div class="Div_Scroll_Content">
    <div id="AlertWindow" class="Div_AlertWindow">
      <input type="button" id="Sure" value="關閉對話框" />
    </div>
  </div>
</div>

<div style="height:1300px; padding-top:200px;">
  <input id="alertButton" type="button" onclick="ShowAlert();" value="顯示對話框" />
</div>
</body>
</html>

三層結構各司何職

  • .Div_Scroll:遮罩層,position:fixed 讓它不隨頁面捲動,opacity:0.6 壓暗背景,z-index:99 確保蓋在內容之上。預設 visibility:hidden,呼叫時才現形。
  • .Div_Scroll_Content:撐出垂直空間的墊片,margin-top:20% 把對話框推到畫面偏上中段。
  • .Div_AlertWindow:對話框本體,margin:auto 完成水平居中。

這份寫法可以更好的地方

用固定寬高去對齊螢幕是脆弱的。 window.screen.availWidth 抓的是實體螢幕尺寸,不是視窗可視區域;在雙螢幕或縮放視窗時會對不上。改用 width:100%; height:100% 搭配 position:fixed; top:0; left:0,就不需要任何 JS 計算。

垂直居中不必靠猜百分比。 現代做法有兩種:一是 top:50%; left:50%; transform:translate(-50%,-50%);二是直接用 Flexbox:

.overlay {
    position: fixed;
    inset: 0;                    /* 等同 top/right/bottom/left 全為 0 */
    background: rgba(128,128,128,.6);
    display: flex;
    align-items: center;         /* 垂直居中 */
    justify-content: center;     /* 水平居中 */
    z-index: 99;
}

遮罩層要用 display 切換。 用 visibility:hidden 的元素仍佔據空間與事件命中範圍,容易誤觸;改 display:none/flex 更乾淨。

無障礙性不能省。 彈出時要將焦點移進對話框、對話框加上 role="dialog" 與 aria-modal="true",並支援 Esc 關閉;關閉後把焦點還給原本的觸發按鈕。背景內容最好設為 inert,避免 Tab 鍵跑到遮罩後面去。

最後,如果目標只是「一個置中對話框」,HTML5 的 <dialog> 元素已經內建了 showModal():它自帶遮罩、自動處理焦點鎖定與 Esc 關閉,並以 ::backdrop 樣本合同化樣式。除非需要支援很舊的瀏覽器,否則不必再手刻一遍。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved