问题
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:
Set a
click
handler for the body to remove your popup.Set a
click
handler for the popup itself that callsstopPropagation()
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