mouse click somewhere else on page (not on a specific div)

前端 未结 4 438
盖世英雄少女心
盖世英雄少女心 2020-12-11 15:29

I want to close a little pop-up box in page when user has clicked anywhere on the page other than box area. how to find it?

相关标签:
4条回答
  • 2020-12-11 16:07

    @jAndy's solution is good, but I wanted to mention Ben Alman's "Outside Events" plugin as well. Here's a quick example using it:

    $("#popup").bind("clickoutside", function(event){
      $(this).hide();
    });
    
    0 讨论(0)
  • 2020-12-11 16:08
    $(document.body).click(function(e){
       var $box = $('#little-pop-up-box-id');
       if(e.target.id !== 'little-pop-up-box-id' && !$.contains($box[0], e.target))
          $box.remove();
    });
    

    e.target is the DOM node which received the click event. I'm checking first if the ID of that element is not the one we are looking for.

    The second check !$.contains($box[0], e.target) makes sure, that the DOM node of invocation is not within the element we want to hide.

    Well, I guess it's plugin time! :

    (function($){
       $.fn.outside = function(ename, cb){
          return this.each(function(){
             var $this = $(this),
                  self = this;
             $(document.body).bind(ename, function tempo(e){
                 if(e.target !== self && !$.contains(self, e.target)){
                    cb.apply(self, [e]);
                    if(!self.parentNode) $(document.body).unbind(ename, tempo);
                 }
             });
          });
       };
    }(jQuery));
    

    synopsis

    $('#container').outside('click', function(e){
        $(this).remove();
    });
    

    Example:

    http://www.jsfiddle.net/qbDKN/30/

    0 讨论(0)
  • 2020-12-11 16:21
    $("html").click(function(){
    //close popup
    });
    
    0 讨论(0)
  • 2020-12-11 16:25

    Grab global click event, or setup transparent div 100%/100% under the pop-up box with such event.

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