2013-07-27 20 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

相關問題