点击页面其他区域隐藏弹出层
弹出层简称pop,隐藏方法有两种。
1. pop上阻止冒泡,document上click隐藏pop
jquery实现
$("#showPop").on("click", function(e) {
$("#pop").show();
$(document).one("click", function() {
$("#pop").hide();
});
e.stopPropagation();
});
$("#pop").on("click", function(e) {
e.stopPropagation();
});
pop show时注册一次document的click,可以减少document click的无谓触发和pop检测。
2. document上click,检测事件源,是否为pop或其子元素,不是则隐藏pop
js实现
$(document).bind('click', function(e) {
var e = e || window.event; //浏览器兼容性
var elem = e.target || e.srcElement;
while (elem) { //循环判断至跟节点,防止点击的是pop子元素
if (elem.id && elem.id == 'pop') {
return;
}
elem = elem.parentNode;
}
$('#pop').css('display', 'none'); //点击的不是pop或其子元素
});
jquery实现
$(document).bind("click", function(e) {
var target = $(e.target);
if (target.parents(".pop").length === 0) {
$(".pop").hide();
}
})
参考:https://www.zhihu.com/question/26391484/answer/32635684
http://www.cnblogs.com/dolphinX/p/3239530.html

浙公网安备 33010602011771号