jQuery:如果在其他位置检测到单击,则隐藏弹出窗口 [英] jQuery: Hide popup if click detected elsewhere

查看:49
本文介绍了jQuery:如果在其他位置检测到单击,则隐藏弹出窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户单击弹出窗口的任何位置或它的孩子,我将尝试隐藏div.这是我到目前为止的代码:

$("body").click(function(){
    var $target = $(event.target);
    if(!$target.is(".popup") || !$target.is(".popup").children()){
        $("body").find(".popup").fadeOut().removeClass('active');
    }
});

它适用于.popup div,但是如果单击了其中的任何子级,则无论如何都会将其隐藏.

解决方案

我认为您真的可以简化一下:

// 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();
});

单击弹出窗口或其任何子项,将导致传播在到达身体之前停止传播.

停止事件传播的演示: http://jsbin.com/ofeso3/edit

I'm trying to hide a div if the user clicks anywhere BUT the popup OR it's children. This is the code I have so far:

$("body").click(function(){
    var $target = $(event.target);
    if(!$target.is(".popup") || !$target.is(".popup").children()){
        $("body").find(".popup").fadeOut().removeClass('active');
    }
});

It works for the .popup div, but if any of it's children are clicked, it hides it anyway.

解决方案

You really could simplify this a bit I think:

// 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();
});

Clicking on the popup, or any of its children will cause propagation to stop before it reaches the body.

Demo of stopping event-propagation: http://jsbin.com/ofeso3/edit

这篇关于jQuery:如果在其他位置检测到单击,则隐藏弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆