您的位置:首页 > Web前端 > JQuery

Jquery 实现弹出框点击自身以外的地方(遮罩层)关闭弹出框

2018-12-20 19:09 441 查看

整个实例在最下面,复制到编辑器上直接看效果

1.HTML部分

<div id="branch">
<div class="branch-header">
<button>点击出现弹出框</button>
</div>
<!-- 弹出框 -->
<div class="branch-proup">
<div class="branch-proup-content">
<!-- 弹出框内容 -->
</div>
</div>
</div>

2.js部分

$(function(){
//点击按钮
var btn = $('#branch .branch-header button');
//弹出框
var proup = $('#branch .branch-proup');

btn.click(function(){
proup.show();
})

//点击弹窗内容以外的地方关闭弹窗
proup.on('click',function (e) {
if($(e.target).closest('#branch .branch-proup-content').length > 0){
alert('弹出框内部被点击了')
}else{
alert('弹出框以外的部分被点击了')
//关闭弹框
proup.hide()
}
});
})

3.核心代码

//$(document) 弹框内容的父容器
$(document).on("click", function (e) {
//closest('element') 选择的是弹窗内容容器
if($(e.target).closest('element').length > 0){
//这里执行点击容器本身执行的事件
}else{
//这里执行点击容器之外的地方的事件(关闭弹窗)
}
});

4.全部源码

jq路径替换成自己的文件路径
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>jq点击自身以为关闭弹出窗</title>
<script src="../js/jquery-3.3.1.js"></script>
<style>
*{margin:0;padding:0}
#branch{
width:100%;
height:auto;
}
/* 按钮 */
#branch .branch-header button{
margin:300px 600px;
}
/* 弹出框 */
#branch .branch-proup{
position: fixed;
top:0;
left:0;
width:100%;
height:100%;
background-color: rgba(0,0,0,.2);
border-radius:5px 5px 0 0;
display:none;
z-index:10;
}
#branch .branch-proup-content{
position: fixed;
top:50%;
left:50%;
width:320px;
height:320px;
background-color:#fff;
border:1px solid #ccc;
border-radius:5px;
margin-top:-160px;
margin-left:-160px;
}
</style>
</head>
<body>
<div id="branch">
<div class="branch-header">
<button>点击出现弹出框</button>
</div>
<!-- 弹出框 -->
<div class="branch-proup">
<div class="branch-proup-content">
<!-- 弹出框内容 -->
</div>
</div>
</div><script type="text/javascript">
$(function(){
//点击按钮
var btn = $('#branch .branch-header button');
//弹出框
var proup = $('#branch .branch-proup');

btn.click(function(){
proup.show();
})

//点击弹窗内容以外的地方关闭弹窗
proup.on('click',function (e) {
if($(e.target).closest('#branch .branch-proup-content').length > 0){
alert('弹出框内部被点击了')
}else{
alert('弹出框以外的部分被点击了')
//关闭弹框
proup.hide()
}
});
})
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: