最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I make this popup box disappear when I click outside? - Stack Overflow

programmeradmin1浏览0评论

/

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?

http://jsfiddle/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?

Share Improve this question asked Feb 22, 2011 at 2:10 mpenmpen 284k281 gold badges892 silver badges1.3k bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9
  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);

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).

发布评论

评论列表(0)

  1. 暂无评论