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
1.0k views
in Technique[技术] by (71.8m points)

jquery - How to hide a popup by clicking outside

I am trying to come up with a way so that once #email-popup or #phone-popup is visible, if the user clicks anywhere EXCEPT the visible popup, then it is going to hide the popup.

My method for hiding the popups in the code below does not work well...

My JQuery so far

$(".email").click(function(){
    $("#email-popup").show("fast");
});
$(".phone").click(function(){
   $("#phone-popup").show();
});

$(document).click(function() {
     $("#email-popup").hide("fast");                        
     $("#phone-popup").hide("fast");
});
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You're close - just stop the propagation when the user clicks within the popups:

$("#email-popup, #phone-popup").on("click", function(e){
  e.stopPropagation();
});

$(".email").on("click", function(e){
  e.stopPropagation();
  $("#email-popup").show("fast");
});

$(".phone").on("click", function(e){
  e.stopPropagation();
  $("#phone-popup").show();
});

Also you have some repeated code in the document click. You're hiding the email popup twice.

$(document).on("click", function() {
  $("#email-popup, #phone-popup").hide("fast");
});

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

...