搜尋框下方的提示層、自訂的下拉選單,都需要「點外面就收起來」的行為。做法是攔截全域點擊事件,判斷目標是不是浮層本身。
下面的代碼執行後,需要重新整理一次才能跑起來。
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>test</title>
<style type="text/css">
.div_d{ padding:10px; border:1px dotted red; position:absolute; display:none; cursor:pointer;}
</style>
<script src="https://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(function(){
$("input[id=search]").focus(function(even){
var pos = $(this).offset();
$(".div_d").css({ left: pos.left, top: pos.top + 20 + "px", display: "block" });
});
document.onclick = function(e){
var e = e ? e : window.event;
var tar = e.srcElement || e.target;
if (tar.id != "search") {
if ($(tar).attr("class") == "div_d") {
$(".div_d").css("display", "block") // 點在浮層內 → 保持顯示
} else {
$(".div_d").css("display", "none"); // 點在外面 → 收起
}
}
}
})
</script>
</head>
<body style="padding-left:300px;">
<input id="search" />
<div class="div_d">
<a href="https://www.poluoluo.com" target="_blank"></a>介紹信息
</div>
</body>
</html>
輸入框 focus 時,先抓自己的位置 offset(),把浮層定位到下方並顯示。全域 onclick 則負責收尾:取得被點擊的元素(e.target,IE 用 e.srcElement),若它不是搜尋框也不是浮層本身,就隱藏。
一、用 stopPropagation 取代 class 名稱比對。目前用 $(tar).attr("class") == "div_d" 判斷,只要浮層內的元素帶了第二個 class,判斷就會失效。更穩健的做法是在浮層上綁 click 時呼叫 event.stopPropagation(),事件就不會冒泡到 document。
$(".div_d").click(function(e){ e.stopPropagation(); });
二、改用 closest 判斷所屬容器。
if ($(tar).closest(".div_d").length === 0) { $(".div_d").hide(); }
這樣無論點到浮層裡多深的子元素,都能正確辨識。
三、避免全域 onclick 覆蓋既有處理器。直接用 document.onclick = ... 會把別人掛的 onclick 洗掉。改用 jQuery 綁定:
$(document).on("click", function(e){
if ($(e.target).closest("#search, .div_d").length === 0) {
$(".div_d").hide();
}
});
順帶一提,範例中的 charset=gb2312 與已失效的 googlecode 連結都是時代產物,實作時請改用 UTF-8 並從正式 CDN 載入 jQuery。