How do I make this popup box disappear when I click outside?

老子叫甜甜 提交于 2019-12-07 15:24:36

问题


http://jsfiddle.net/mnbayazit/by3zy/2/

I want the popup to disappear when I click somewhere on the background. Problem is, it disappears when I click an [X] or the popup itself.

Imagine it being a calendar-picker if that makes my intentions more clear.

How can I get it to do that?


回答1:


  1. Set a click handler for the body to remove your popup.

  2. Set a click handler for the popup itself that calls stopPropagation() on the event, to prevent it from bubbling up to the body.

Roughly:

function showMyPopup(){
  ...
  $(myPopupDiv).click(function(e){
    e.stopPropagation();
  });
}
function closeMyPopup(){
  ...
}
$(document.body).click(closeMyPopup);



回答2:


The basic jist with this technique is to have a wrapping (or independent element layered with z-index) that 'captures' the click event, and hides the elements you desire. I've updated your fiddle with an example of how this would work, except imagine that the blanket element would have a height and width of 100% (to cover the entire viewport).



来源:https://stackoverflow.com/questions/5073336/how-do-i-make-this-popup-box-disappear-when-i-click-outside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!