我试图隐藏div如果用户点击任何地方但弹出窗口或它的孩子.这是我到目前为止的代码:
$("body").click(function(){
var $target = $(event.target);
if(!$target.is(".popup") || !$target.is(".popup").children()){
$("body").find(".popup").fadeOut().removeClass('active');
}
});
Run Code Online (Sandbox Code Playgroud)
它适用于.popup div,但是如果它的任何一个孩子被点击,它仍会隐藏它.
Sam*_*son 84
你真的可以简化这一点我想:
// If an event gets to the body
$("body").click(function(){
$(".popup").fadeOut().removeClass("active");
});
// Prevent events from getting pass .popup
$(".popup").click(function(e){
e.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)
单击弹出窗口或其任何子项将导致传播在到达正文之前停止.
停止事件传播的演示:http://jsbin.com/ofeso3/edit
小智 8
我正在使用一个非常简单的代码: -
$(document).click(function(e){
if($(e.target).closest('#popupdivID').length != 0) return false;
$('#popupdivID').hide();
});
Run Code Online (Sandbox Code Playgroud)
这对于下拉菜单也很有用.如果您单击下拉菜单并查看列表,然后单击文档中的其他位置,则应关闭该下拉列表.我也使用了相同的代码.
谢谢!!