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.target是DOM 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/
| 归档时间: |
|
| 查看次数: |
9581 次 |
| 最近记录: |