jquery三个关闭弹出层的小示例
在开发应用中我们做了一个弹出层,有时我们会做一个关闭按钮,这样点击关闭就可以把弹出层关闭了,但是有时希望只要不点击弹出层内就自动关闭弹出层了,下面我总结了三个实例。
例1
. 代码如下:
<!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>
<p class="pop"></p>
</body>
</html>
例2,点击自身以外地方关闭弹出层
. 代码如下:
<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() {
$("p.down").click(function(e) {
e.stoppropagation();
$("p.con").removeclass("hide");
});
$(document).click(function() {
if (!$("p.con").hasclass("hide")) {
$("p.con").addclass("hide");
}
});
});
</script>
<body>
<p class="down">click</p>
<p class="con hide">show-area</p>
</body>
</html>
例3
. 代码如下:
<!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>
<p id="box">打开我了,点空白关闭啊,谢谢</p>
<span class="btn">打开弹出层</span>
</body>
</html>
上一篇: jquery实现手风琴效果实例代码