实例代码如下:
html
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>点击空白处关闭弹窗</title>
</head>
<body>
<span class="btn btn-pop">点我</span>
<div class="pop">
<p>这是面是弹窗内容</p>
<span class="btn close">关闭</span>
</div>
</body>
</html>
css
.btn{
display: inner-block;
padding: 5px;
border: 1px red solid;
border-radius: 6px;
cursor: pointer;
}
.pop{
width: 200px;
height: 200px;
border: 2px solid red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
display: none;
padding: 10px;
}
js - 两种实现方式
var pop = $('.pop');
$('.btn-pop').on('click', function(e){
e.stopPropagation();
pop.show();
});
$('.close').on('click', function(){
pop.hide();
});
$(document).click(function(e){
// 方法1
// if($(':not(.pop)')){
// pop.hide();
// }
// 方法2
if(!pop.is(e.target) && pop.has(e.target).length === 0){
pop.hide();
}
});
网友评论