我正在嘗試使下拉菜單顯示您單擊按鈕時的內容,並隱藏當您單擊下拉菜單中的任何位置時隱藏下拉菜單。當單擊任何位置時,jQuery隱藏下拉菜單,但菜單
我有一些代碼工作,只要不點擊菜單時關閉,但是當菜單關閉時單擊文檔時,它會顯示菜單,因此無論點擊的位置如何都會持續切換。
$(document).click(function(event) {
if ($(event.target).parents().index($('.notification-container')) == -1) {
if ($('.notification-container').is(":visible")) {
$('.notification-container').animate({
"margin-top": "-15px"
}, 75, function() {
$(this).fadeOut(75)
});
} else {
//This should only show when you click: ".notification-button" not document
$('.notification-container').show().animate({
"margin-top": "0px"
}, 75);
}
}
});
描述你的代碼;它將click事件綁定到整個'document'文件,當觸發該事件時,它檢查目標(clicked)元素是否具有類「.notification-container」的父類,如果是,則檢查是否有該類的元素是可見的。如果是這樣,它會隱藏(動畫)所有具有「.notification-container」類的元素,否則它會顯示(動畫)它們。 – Stefan 2012-01-10 11:39:13
最好的解決方案是[stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element] [1]。 [1]:http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element – lightofsouls 2013-06-28 08:31:27
嗨,老兄,你能不能接受一個答案? :) – epoch 2016-05-06 07:08:37