實例代碼如下:
html
<!DOCTYPE html>
<html>
<head>
<script src="http://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();
}
});