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

前端 未结 2 1728
野的像风
野的像风 2020-11-27 22:48

I have a

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 cli
相关标签:
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/

    0 讨论(0)
  • 2020-11-27 23:48

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

    0 讨论(0)
提交回复
热议问题