我正在尝试使下拉菜单显示您单击按钮时的内容,并隐藏当您单击下拉菜单中的任何位置时隐藏下拉菜单。当单击任何位置时,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