【发布时间】:2012-01-10 08:42:47
【问题描述】:
我正在尝试使我的下拉菜单在您单击按钮时显示,并在您单击下拉菜单以外的任何位置时隐藏。
我有一些代码在工作,就在您单击菜单时不关闭,但是当您在菜单关闭时单击文档时,它会显示菜单,因此无论您单击何处,它都会不断切换。
$(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,当该事件被触发时,它会检查target(clicked)元素是否有任何具有“.notification-container”类的父元素,如果有,它会检查是否有任何元素具有该类可见。如果是这样,它会隐藏(动画)类“.notification-container”的所有元素,否则它会显示(动画)它们。 -
最好的解决方案是 [stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element][1]。 [1]:stackoverflow.com/questions/152975/…
-
嘿伙计,你介意接受一个答案吗? :)
标签: javascript jquery jquery-events