彈出層(Modal/Dialog)由兩個主要元素組成:
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>JS + CSS 置中彈出層與半透明遮罩</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: "Microsoft JhengHei", sans-serif; line-height: 1.6; }
/* 遮罩層 */
#overlay {
position: fixed;
top: 0; left: 0; right: 0; bottom: 0;
background: rgba(0, 0, 0, 0.5); /* 現代瀏覽器 */
background: #000; /* IE8 fallback */
opacity: 0.5;
filter: Alpha(opacity=50); /* IE8- */
display: none;
z-index: 999;
}
/* 彈出內容層 */
#popup {
position: fixed;
top: 50%; left: 50%;
width: 400px; height: 300px;
margin: -150px 0 0 -200px; /* 負邊距置中 */
background: #fff;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0,0,0,0.3);
padding: 20px;
display: none;
z-index: 1000;
overflow-y: auto;
}
.close-btn {
position: absolute;
top: 10px; right: 15px;
font-size: 24px; font-weight: bold;
color: #999; cursor: pointer;
text-decoration: none;
}
.close-btn:hover { color: #333; }
/* 觸發按鈕 */
.trigger-btn {
padding: 10px 20px; background: #007bff; color: #fff;
border: none; border-radius: 4px; cursor: pointer; font-size: 16px;
}
.trigger-btn:hover { background: #0056b3; }
</style>
</head>
<body>
<button class="trigger-btn" onclick="openPopup()">點擊開啟彈出層</button>
<div id="overlay" onclick="closePopup()"></div>
<div id="popup">
<a href="javascript:void(0);" class="close-btn" onclick="closePopup()" title="關閉">×</a>
<h2>彈出層標題</h2>
<p>這裡可以放置任意 HTML 內容:表單、圖片、文字說明等。</p>
<p>點擊遮罩層或右上角 × 即可關閉。</p>
</div>
<script>
const overlay = document.getElementById("overlay");
const popup = document.getElementById("popup");
function openPopup() {
overlay.style.display = "block";
popup.style.display = "block";
document.body.style.overflow = "hidden"; // 防止背景捲動
}
function closePopup() {
overlay.style.display = "none";
popup.style.display = "none";
document.body.style.overflow = "";
}
// ESC 鍵關閉
document.addEventListener("keydown", (e) => {
if (e.key === "Escape" && popup.style.display === "block") {
closePopup();
}
});
</script>
</body>
</html>
#popup {
position: fixed;
top: 50%; left: 50%;
width: 400px; height: 300px;
margin: -150px 0 0 -200px; /* 高度/寬度的一半 */
}
這是傳統且相容性最好的置中方式,支援 IE8+。現代專案也可改用 Flexbox:
#popup {
position: fixed;
top: 0; left: 0; right: 0; bottom: 0;
display: flex; align-items: center; justify-content: center;
/* 內容容器再包一層 div 設定具體寬高 */
}
#overlay {
background: rgba(0, 0, 0, 0.5); /* 標準 */
background: #000; opacity: 0.5; filter: Alpha(opacity=50); /* IE8 降級 */
}
z-index: 999 (遮罩) < z-index: 1000 (彈出層),確保彈出層永遠在最上層。
實際專案中建議封裝為可複用的函式或 Class:
class Modal {
constructor(options = {}) {
this.content = options.content || "";
this.onClose = options.onClose || (() => {});
this._createElements();
this._bindEvents();
}
_createElements() {
this.overlay = document.createElement("div");
this.overlay.className = "modal-overlay";
this.overlay.innerHTML = `
<div class="modal-content">
<button class="modal-close" aria-label="關閉">×</button>
<div class="modal-body">${this.content}</div>
</div>
`;
document.body.appendChild(this.overlay);
// 強制重繪以觸發 CSS transition
requestAnimationFrame(() => this.overlay.classList.add("show"));
}
_bindEvents() {
this.overlay.querySelector(".modal-close").onclick = () => this.close();
this.overlay.onclick = (e) => { if (e.target === this.overlay) this.close(); };
this._escHandler = (e) => { if (e.key === "Escape") this.close(); };
document.addEventListener("keydown", this._escHandler);
}
close() {
this.overlay.classList.remove("show");
this.overlay.addEventListener("transitionend", () => {
this.overlay.remove();
document.removeEventListener("keydown", this._escHandler);
this.onClose();
}, { once: true });
}
}
// 使用方式
new Modal({
content: "<h3>動態產生的彈出層</h3><p>內容可為任意 HTML</p>",
onClose: () => console.log("彈出層已關閉")
});
aria-label="關閉"。role="dialog" 與 aria-modal="true" 標記彈出層。掌握這些基礎與進階技巧,即可輕鬆實作出美觀、無障礙且可維護的彈出層元件。