鼠标单击页面上的其他位置(而不是特定的div)

cou*_*011 12 javascript jquery

当用户点击页面上除框区域以外的任何位置时,我想在页面中关闭一个小弹出框.怎么找到它?

jAn*_*ndy 17

$(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();
});
Run Code Online (Sandbox Code Playgroud)

e.targetDOM node收到的click event.我先检查ID那个元素是不是我们要找的那个元素.

第二次检查!$.contains($box[0], e.target)确保DOM node of invocation不在我们想要隐藏的元素.

好吧,我猜这是插件时间!:

(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));
Run Code Online (Sandbox Code Playgroud)

概要

$('#container').outside('click', function(e){
    $(this).remove();
});
Run Code Online (Sandbox Code Playgroud)

例:

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