跳出式視窗範例
以下範例不使用 `<dialog>`,而是透過一般的 `<div>` 搭配 CSS 與 JavaScript 建立跳出式視窗。
## HTML
```html
<button id="openBtn">開啟視窗</button>
<!-- 遮罩與跳出式視窗 -->
<div id="modalOverlay" class="modal-overlay" aria-hidden="true">
<div
class="modal"
role="dialog"
aria-modal="true"
aria-labelledby="modalTitle"
>
<button id="closeBtn" class="close-btn" aria-label="關閉視窗">
×
</button>
<h2 id="modalTitle">跳出式視窗</h2>
<p>這是一個使用 HTML、CSS 和 JavaScript 建立的視窗。</p>
<button id="confirmBtn">確定</button>
</div>
</div>
```
## CSS
```css
/* 基本按鈕樣式 */
button {
padding: 10px 18px;
border: none;
border-radius: 6px;
background-color: #2563eb;
color: white;
cursor: pointer;
}
button:hover {
background-color: #1d4ed8;
}
/* 遮罩 */
.modal-overlay {
display: none;
position: fixed;
inset: 0;
z-index: 1000;
/* 水平置中,也可同時垂直置中 */
justify-content: center;
align-items: center;
background-color: rgba(0, 0, 0, 0.5);
}
/* 開啟狀態 */
.modal-overlay.show {
display: flex;
}
/* 視窗本體 */
.modal {
position: relative;
width: min(90%, 420px);
padding: 28px;
border-radius: 10px;
background-color: white;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}
/* 關閉按鈕 */
.close-btn {
position: absolute;
top: 8px;
right: 10px;
padding: 2px 8px;
background: transparent;
color: #555;
font-size: 28px;
}
.close-btn:hover {
background: #eee;
color: #000;
}
```
## JavaScript
```javascript
const openBtn = document.querySelector("#openBtn");
const closeBtn = document.querySelector("#closeBtn");
const confirmBtn = document.querySelector("#confirmBtn");
const modalOverlay = document.querySelector("#modalOverlay");
function openModal() {
modalOverlay.classList.add("show");
modalOverlay.setAttribute("aria-hidden", "false");
// 將焦點移到關閉按鈕
closeBtn.focus();
}
function closeModal() {
modalOverlay.classList.remove("show");
modalOverlay.setAttribute("aria-hidden", "true");
// 關閉後將焦點移回開啟按鈕
openBtn.focus();
}
openBtn.addEventListener("click", openModal);
closeBtn.addEventListener("click", closeModal);
confirmBtn.addEventListener("click", closeModal);
/* 點擊遮罩區域時關閉 */
modalOverlay.addEventListener("click", function (event) {
if (event.target === modalOverlay) {
closeModal();
}
});
/* 按下 Esc 鍵時關閉 */
document.addEventListener("keydown", function (event) {
if (event.key === "Escape" && modalOverlay.classList.contains("show")) {
closeModal();
}
});
```
### 核心概念
- `position: fixed` 讓遮罩覆蓋整個瀏覽器視窗。
- `display: flex` 搭配 `justify-content: center`,讓視窗水平置中。
- `align-items: center` 會讓視窗同時垂直置中。
- JavaScript 透過加入或移除 `.show` 類別控制視窗顯示與隱藏。
- 也加入了點擊遮罩、關閉按鈕及 `Esc` 鍵關閉功能。
相關學習地圖、教學課程
F2E 網站前端工程