2013-07-27 21 views
2

Here's the fiddle.当我点击打开它的链接时,为什么这个div不会关闭?

的代码包括:

$('.icon').click(function() { 
    $('.foo').toggle(); 
}); 
$(document).mouseup(function (e) { 
    var container = $('.foo'); 

    if (!container.is(e.target) // if the target of the click isn't the container... 
    && 
    container.has(e.target).length === 0) // ... nor a descendant of the container 
    { 
     container.hide(); 
    } 
}); 

我可以使用链接来打开它,代码关闭它,当一个点击它的外面,但我不能打开它的链接关闭原来。

+0

http://jsfiddle.net/gT5BT/104/ – rps

回答

1

您错过了if语句中的检查,看看是否为.icon是目标。

http://jsfiddle.net/gT5BT/100/

var foo = $('.foo'), icon = $('.icon'); 

icon.click(function() { 
    foo.toggle(); 
}); 

$(document).mouseup(function (e) { 
    if (!foo.is(e.target) && !icon.is(e.target) && !foo.has(e.target).length) 
     foo.hide(); 
}); 
+0

准确地说。刚刚准备发布我自己的解决方案,解决这个问题。谢谢! – user1452893

4

您隐藏并再次显示。只是评论container.hide();并尝试点击.icon

要解决此问题,只需检查全球mouseup事件处理程序中的.icon容器。 http://jsfiddle.net/55DSp/

+0

不,不工作,因为它无法通过单击外界关闭,限制了接近.icon。 – user1452893

+0

无论如何,但不是解决方案。 – user1452893

+0

解决方案更新了答案。 – twil

相关问题