Я пытаюсь сделать так, чтобы мое раскрывающееся меню показывалось, когда вы нажимаете кнопку, и скрывалось, когда вы щелкаете где угодно, кроме раскрывающегося меню.
У меня работает некоторый код, который не закрывается при нажатии на меню, однако, когда вы щелкаете документ, когда меню закрыто, оно показывает меню, поэтому оно постоянно переключается независимо от того, где вы щелкаете.
$(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);
}
}
});
Функция jQuery closest () может использоваться, чтобы увидеть, находится ли щелчок внутри меню:
$('body').click(function(e) {
if ($(e.target).closest('.notification-container').length === 0) {
// close/animate your div
}
});
попробуйте что-то вроде:
$(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)});
}
}
});
$(".notification-button").click(function(event){
event.stopPropagation();
$('.notification-container').show().animate({"margin-top":"0px"}, 75);
});