How to close/hide a DIV element when clicking outside of it (but not inside)

纵然是瞬间 提交于 2019-11-26 21:06:40

Toggle a flag on popup hover:

JSBin demo

var $pop   = $('#popup'),
    notHov = 1; // Hover flag

$pop.hover(function(){ notHov^=1; }); // Toggle flag on hover

$(document).on('mouseup keyup', function( e ){
  if(notHov||e.which==27) $pop.fadeOut();
});

Note:
if somewhere on the page you have an element the prevents the mouseup event to bubble up the DOM tree reaching document (in order to be registered), you might want to create a full-screen (like an page-overlay) popup wrapper to register the click events, changing in the code above just the selector: instead of $(document) would be $('#popupWrapper')

Probably the easiest way to do this will be to monitor clicks on the entire document, and ignore it if it's not that element. If it is, then hide it.

(function(div) {
    $(document).click(function(e) {
        if (e.srcElement !== div) $(div).hide();
    });
})($('div')[0]);

Edit: Derp, misunderstood, click inside should stay, otherwise hide... invert the equality check.

http://jsfiddle.net/robert/QcPx4/

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