场景:点击一个按钮弹出一个对话框/气泡,点击空白区域隐藏对话框/气泡;
html:
<button id="btn">按钮</button>
<div class="tips"></div>
css:
.tips{
width: 100px;
height: 100px;
background: red;
display: none;
}
js:
//方法一:适用于按钮(有聚焦、失焦事件)
$("#btn").on("click",function(){
$(".tips").show();
});
$("#btn").on("blur",function(){
$(".tips").hide();
});
//方法二:适用所有元素
$("#btn").on("click",function(e){
e.stopPropagation();
$(".tips").show();
});
$(document).on("click",function(){
$(".tips").hide();
});
//方法二点击`$(".tips")`不关闭
$(".tips").on("click",function(e){
e.stopPropagation();
});
//方法三:适用所有的元素
$("#btn").on("click",function(e){
$(".tips").show();
$(document).one("click",function(){
$(".tips").hide();
});
e.stopPropagation();
});
//方法三点击`$(".tips")`不关闭
$(".tips").on("click",function(e){
e.stopPropagation();
});
效果如下: