**直接使用 jQuery UI Dialog**,內建模態遮罩 (`modal: true`),無需手動寫遮罩層、z-index 管理。
<div id="dialog" title="標題" style="display:none;">
這裡是彈出內容,可以包含表單、表格、任意 HTML。
</div>
<button id="opener">開啟彈窗</button>
<script>
$(function() {
$("#dialog").dialog({
autoOpen: false,
modal: true, // ★ 關鍵:開啟模態遮罩,鎖定背景互動
width: 500,
height: 400,
resizable: false,
draggable: true,
closeOnEscape: true,
buttons: {
"確定": function() { $(this).dialog("close"); },
"取消": function() { $(this).dialog("close"); }
}
});
$("#opener").click(function() { $("#dialog").dialog("open"); });
});
</script>
$("#opener").click(function() {
$("").dialog({
modal: true,
title: "動態載入",
width: 600,
open: function() {
var $dlg = $(this);
$.get("/api/content/123", function(html) {
$dlg.html(html); // 填入內容
});
},
close: function() { $(this).dialog("destroy").remove(); } // 關閉銷毀
});
});
手動遮罩 (不使用 Dialog) 實作原理
若堅持自行實作:
- 建立遮罩 ``,CSS:`position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:9998; display:none;`
- 彈出內容容器 ``,CSS:`position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); z-index:9999; display:none;`
- JS:`$('.overlay, .popup').fadeIn();` 關閉時 `fadeOut()`。
但 **jQuery UI Dialog 已完美封裝上述邏輯**,包含焦點管理、Esc 關閉、拖曳、調整大小、無障礙 (ARIA) 支援,**強烈建議直接使用**。