在開發中我們常會製作彈出層。除了放置關閉按鈕,很多時候還希望「只要點擊彈出層以外的區域就自動關閉」。本文總結了三種實現方式。
透過判斷點擊的目標是否在彈出層之內來決定是否關閉:
<!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>
<title>點擊空白處關閉彈出窗口</title>
<meta http-equiv="content-type" content="text/html;charset=gb2312">
<style type="text/css">.pop{width:200px;height:130px;background:#080;}</style>
<script type="text/javascript" src="/ajaxjs/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(function(){
$(document).bind("click",function(e){
var target = $(e.target);
if(target.closest(".pop").length == 0){
$(".pop").hide();
}
})
})
</script>
</head>
<body><div class="pop"></div></body>
</html>
透過 stopPropagation 阻止事件冒泡,並用 class 切換顯示狀態:
<html>
<style>.hide{display:none;}</style>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("div.down").click(function(e) {
e.stopPropagation();
$("div.con").removeClass("hide");
});
$(document).click(function() {
if (!$("div.con").hasClass("hide")) { $("div.con").addClass("hide"); }
});
});
</script>
<body>
<div class="down">click</div>
<div class="con hide">show-area</div>
</body>
</html>
透過判斷 stopPropagation 是否存在來兼容不同瀏覽器:
<!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>
<title>jQuery 點擊空白處關閉彈出層</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<style type="text/css">#box{width:300px;height:200px;border:1px solid #000;display:none; margin:0 auto;}.btn{color:red;}</style>
<script src="https://www.honoer.com/Public/Js/jQuery/jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$(".btn").click(function(event){
var e=window.event || event;
if(e.stopPropagation){ e.stopPropagation(); }else{ e.cancelBubble = true; }
$("#box").show();
});
$("#box").click(function(event){
var e=window.event || event;
if(e.stopPropagation){ e.stopPropagation(); }else{ e.cancelBubble = true; }
});
document.onclick = function(){ $("#box").hide(); };
})
</script>
</head>
<body>
<div id="box">打開我了,點空白關閉啊,謝謝</div>
<span class="btn">打開彈出層</span>
</body>
</html>