body { overflow: hidden; }。<style>
.modal-overlay {
position: fixed; inset: 0; background: rgba(0,0,0,0.5);
z-index: 1050; display: none;
display: flex; align-items: center; justify-content: center;
}
.modal-dialog {
background: white; padding: 24px; border-radius: 8px;
min-width: 300px; max-width: 90%; box-shadow: 0 4px 20px rgba(0,0,0,0.2);
}
body.modal-open { overflow: hidden; padding-right: 17px; } /* 防止捲動條跳動 */
</style>
<div class="modal-overlay" id="globalModal">
<div class="modal-dialog">
<h4 id="modalTitle">提示</h4>
<p id="modalBody"></p>
<button class="btn btn-primary" id="modalConfirm">確定</button>
<button class="btn btn-secondary" id="modalCancel" style="margin-left:8px">取消</button>
</div>
</div>
<button id="openModal">開啟鎖定提示</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
const $overlay = $("#globalModal");
const $title = $("#modalTitle");
const $body = $("#modalBody");
const $confirm = $("#modalConfirm");
const $cancel = $("#modalCancel");
let resolvePromise = null;
function openModal(title, body, showCancel = false) {
return new Promise(resolve => {
$title.text(title);
$body.html(body);
$cancel.toggle(showCancel);
$overlay.fadeIn(200);
$("body").addClass("modal-open");
resolvePromise = resolve;
});
}
$confirm.on("click", () => { closeModal(true); });
$cancel.on("click", () => { closeModal(false); });
$overlay.on("click", e => { if (e.target === $overlay[0]) closeModal(false); }); // 點遮罩關閉
function closeModal(result) {
$overlay.fadeOut(200, () => $("body").removeClass("modal-open"));
if (resolvePromise) { resolvePromise(result); resolvePromise = null; }
}
// ESC 鍵關閉
$(document).on("keydown", e => { if (e.key === "Escape" && $overlay.is(":visible")) closeModal(false); });
// 使用範例
$("#openModal").on("click", async () => {
const confirmed = await openModal("確認操作", "此操作不可逆,確定繼續?", true);
if (confirmed) alert("執行核心邏輯...");
else alert("已取消");
});
// 簡易 alert 替代
window.alert = function(msg) {
return openModal("系統提示", msg);
};
</script>
role="dialog" aria-modal="true" aria-labelledby="modalTitle"。$confirm.trigger("focus")。focus-trap 庫)。<dialog id="nativeModal">
<h4>標題</h4>
<p>內容</p>
<menu><button id="ok">確定</button><button id="cancel">取消</button></menu>
</dialog>
<script>
const dialog = document.getElementById("nativeModal");
document.getElementById("ok").onclick = () => dialog.close(true);
document.getElementById("cancel").onclick = () => dialog.close(false);
async function show() { const result = await dialog.showModal(); console.log(result); }
</script>
優勢: 瀏覽器原生處理遮罩、焦點陷阱、ESC 關閉、無障礙,**零依賴、效能最佳**。