Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

jQuery: Hide popup if click detected elsewhere

I'm trying to hide a div if the user clicks anywhere BUT the popup OR its 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');
    }
});

This works for the .popup div, but if any of its children are clicked, it hides it anyway.

question from:https://stackoverflow.com/questions/2329816/jquery-hide-popup-if-click-detected-elsewhere

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...