點擊按鈕開啟 Modal,點擊 Modal 內容區**不關閉**,點擊 Modal **外部空白區域**才關閉。若直接在 `document` 綁定 click 關閉,按鈕點擊會冒泡觸發關閉,導致 Modal 閃現即消失。
// ❌ 錯誤:按鈕點擊冒泡到 document,Modal 立即關閉
$("#btn").on("click", function () { $("#modal").show(); });
$(document).on("click", function () { $("#modal").hide(); });
// 1. Modal 內容區阻止冒泡
$("#modal").on("click", function (e) {
e.stopPropagation(); // 關鍵:事件不再向上傳遞
});
// 2. document 使用 one():點擊一次後自動解綁
$("#btn").on("click", function (e) {
e.stopPropagation(); // 按鈕點擊也不冒泡
$("#modal").show();
// 只監聽下一次 document click
$(document).one("click", function (e) {
// 此時 e.target 不會是 #modal 內部元素(因已阻止冒泡)
$("#modal").hide();
});
});
.one() 觸發後**自動移除監聽器**,避免疊加多層關閉邏輯。class Modal {
constructor(triggerSel, modalSel) {
this.$trigger = $(triggerSel);
this.$modal = $(modalSel);
this.bind();
}
bind() {
this.$trigger.on("click", (e) => {
e.stopPropagation();
this.open();
});
this.$modal.on("click", (e) => e.stopPropagation());
}
open() {
this.$modal.show();
// 使用 one 確保只關閉一次
$(document).one("click", () => this.close());
}
close() {
this.$modal.hide();
}
}
// 使用
new Modal("#btn", "#modal");
<div class="modal-overlay">
<div class="modal-content">...</div>
</div>
.modal-overlay { position:fixed; inset:0; background:rgba(0,0,0,.5); display:none; }
.modal-content { position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); }
$(".modal-overlay").on("click", function (e) {
if (e.target === this) $(this).hide(); // 僅點擊遮罩本身關閉
});
$(".modal-content").on("click", e => e.stopPropagation());
優點:視覺層級清晰、無需 `document` 全域監聽、支援 ESC 鍵關閉擴展。
const btn = document.getElementById("btn");
const modal = document.getElementById("modal");
btn.addEventListener("click", (e) => {
e.stopPropagation();
modal.style.display = "block";
document.addEventListener("click", closeOnce, { once: true }); // {once:true} 等同 one()
});
modal.addEventListener("click", (e) => e.stopPropagation());
function closeOnce() {
modal.style.display = "none";
}
核心模式:**內部阻止冒泡(`stopPropagation`)+ 外部一次性監聽(`one`/`{once:true}`)**。避免全域持久監聽、邏輯耦合與重複綁定。遮罩層方案在 UI/UX 上更優,建議優先採用。