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

女生的网名这么多〃 提交于 2019-11-26 12:17:44

问题


I have a <div> that exists on a page and I need to make it so that when the user clicks outside of that element it will become hidden, but if the user clicks somewhere within the element, then it should stay.

I tried using
e.stopPropagation();
and
e.preventDefault();

adding it to the click event of that certain DIV but that didn\'t work.

Thanks!


回答1:


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




回答2:


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/



来源:https://stackoverflow.com/questions/6140278/how-to-close-hide-a-div-element-when-clicking-outside-of-it-but-not-inside

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