Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$(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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...