點一下按鈕跳出浮層、再點別的地方自動收起——這個看似簡單的需求,細節其實不少:位置要跟著觸發點跑、點擊事件不能冒泡到 document 把浮層立刻關掉。以下是一個可直接運作的完整範例。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>浮層示例</title>
<script type="text/javascript" src="../Javascript/jquery-1.6.js"></script>
<style type="text/css">
#choice_list_district { height:50px; }
#tab td { cursor:pointer; }
</style>
<script type="text/javascript">
$(function () {
// 綁定開關事件
$("#choice_list_district a").click(function (e) {
if ($("#divObj").css("display") == "none") {
e.stopPropagation(); // 關鍵:避免冒泡到 document 被立刻關閉
var offset = $(e.target).offset();
// 讓浮層出現在被點擊元素的下方
$("#divObj").css({
top: offset.top + $(e.target).height() + "px",
left: offset.left
});
$("#divObj").show();
} else {
$("#divObj").hide();
}
});
// 點擊空白處自動收起
$(document).click(function (event) { $("#divObj").hide(); });
// 點選表格中的儲存格,把內容帶回輸入框
$("#tab tr td").click(function (event) {
$("#aaa").val($(this).html());
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="choice_list_district">
<a href="#">點我開啟浮層</a>
</div>
<div id="divObj"
style="position: absolute; width:200px; height:200px; background:blue;
border:1px solid #000; display:none; z-index:9999;">
<table id="tab">
<tr><td>aaa</td></tr>
<tr><td>bbb</td></tr>
</table>
</div>
<div style="position:absolute; top:200px; left:200px;">
<input type="text" id="aaa" />
</div>
</div>
</form>
</body>
</html>
stopPropagation 的位置。必須在 show() 之前呼叫,否则事件會先冒泡上去,浮層才剛打開就被 document 的 click 關掉。
判斷顯示狀態。用 .css("display") 只能抓到內聯樣式;若初始狀態來自外部 CSS,改用 $("#divObj").is(":visible") 或 .toggle() 更可靠。
邊界處理。浮層若貼近視窗右緣或底部,記得判斷 $(window).width() 與 height(),必要時翻转到觸發點上方顯示,避免被裁掉。
z-index。這裡給了 9999,實務上要與 modal、tooltip 一起規劃層級,否則容易互相遮蓋。