2012-03-12 56 views
3

我得到了一个DIV绝对定位在页面上的其他元素之上,我希望它在某处被点击时消失,但不在该绝对定位的div内(或其子元素之一)。让div消失,onClick“无处不在,但......”

我正在使用jQuery的事件传播($(document).on(...))页面上的所有点击事件。

我想有一个通用的解决方案,而不是白名单或黑名单的标签,班请。

我不是在寻找'在绝对DIV和其他内容之间放置一个透明图层'的解决方案,那将是我最后一次重新解决的解决方法。

THX

+0

本页面可能会有所帮助:http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element – Rondel 2012-03-12 14:27:03

回答

0
$(document).on('click', function(e) { 
    if (!(e.target.id=='myID' || $(e.target).parents('#myID').length>0)) { 
     //do something 
    } 
}); 

FIDDLE

+0

获胜者,因为选择父母()而不是最接近的(),请参阅http://jsperf.com/jquery-parents-vs-closest/2 – ezmilhouse 2012-03-12 15:13:23

3
$('html').click(function() { 
    //Hide whatever you want to hide 
}); 

$('#your_div').click(function(e){ 
    e.stopPropagation(); 
}); 

,你也可以尝试this

1

你可以使用e.target检查什么已被点击

$(document).on("click", "*", function(e) { 
    if(e.target.id !== 'yourdivid'){ 
     $('#yourdivid').hide(); 
    } 
    //Hide whatever you want to hide 
}); 

编辑 - 如果你还需要检查孩子你可以做这样的

$(document).on("click", "*", function(e) { 
    //check if the target is your div or a child of your div 
    if($(e.target).closest('div#yourdivid').length !== 1){ 
     $('#yourdivid').hide(); 
    } 
    //Hide whatever you want to hide 
}); 
+0

这不起作用如果你点击正文,你必须点击一个元素。 http://jsfiddle.net/khKb5/1/ – Alex 2012-03-12 14:31:47

0

http://jsfiddle.net/khKb5/

元素

jQuery:

$(document).on("click", function(e) { 
    if($(e.target).closest('#box').length != 1){ 
     $('#box').hide(); 
    } 
}); 

这也适用,如果你直接点击body上的某个地方。