前言
如果想直接测试看疗效html点击按钮弹出窗口,源码放在文章前面,关键地方有注释
应用场景:有一个按钮。 点击后会弹出一个弹框,里面放置了一些内容。 点击弹出框本身并不会关闭弹出框,但点击弹出框会认为描边图层弹出框会关闭。
HTML部分
<div id="branch">
<div class="branch-header">
<button>点击出现弹出框</button>
</div>
<div class="branch-proup">
<div class="branch-proup-content">
</div>
</div>
</div>
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();
}
});
})
核心代码
// $(document) 弹框内容的父容器
$(document).on('click', function(e) {
// closest('element') 选择的是弹窗内容容器
if ($(e.target).closest('element').length > 0) {
// 这里执行点击容器本身执行的事件
} else {
// 这里执行点击容器之外的地方的事件(关闭弹窗)
}
});
所有源代码
<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="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<style>
* {
margin: 0;
padding: 0
}
#branch {
width: 100%;
height: auto;
}
/* 按钮 */
#branch .branch-header button {
margin: 300px 600px;
}
/* 弹出框 */
#branch .branch-proup {
display: none;
position: fixed;
top: 0;
left: 0;
z-index: 10;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, .2);
border-radius: 5px 5px 0 0;
}
#branch .branch-proup-content {
position: fixed;
top: 50%;
left: 50%;
width: 320px;
height: 320px;
border: 1px solid #ccc;
margin-top: -160px;
margin-left: -160px;
background-color: #fff;
border-radius: 5px;
}
</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>
如果这篇文章对您有帮助,我很高兴能为您提供帮助。
当然,如果你觉得文章中有什么地方让你觉得不合理,或者有更简单的实现方式,或者有不明白的地方html点击按钮弹出窗口,希望你听完后可以在评论中指出它。 我会看到然后尽快回复你。
发表评论