我正在使用fadeToggle
打开/关闭div
。如何通过点击外面的任何地方关闭div
?
我尝试了以下内容:
var dropDown = jQuery('.dropdown-menu');
jQuery('.menu-nav').click(function () {
dropDown.fadeToggle('fast');
});
jQuery('div:not(.menu-nav, .dropdown-menu)').click(function () {
dropDown.fadeOut('fast');
});
div
会立即打开和关闭。甚至可以使用fadeToggle
吗?
答案 0 :(得分:2)
将事件处理程序附加到click
上的document
事件。发生点击时,请检查target
以确定是否点击了.dropdown-menu
或.menu-nav
。如果没有,则隐藏菜单。
var dropDown = jQuery('.dropdown-menu');
jQuery('.menu-nav').click(
function (e) {
dropDown.fadeToggle('fast');
e.preventDefault();
}
);
jQuery('div:not(.menu-nav, .dropdown-menu)').click(
function (e) {
dropDown.fadeOut('fast');
e.preventDefault();
}
);
$(document).on("click", function(e){
var $target = $(e.target);
if(!$target.is(".menu-nav") && !$target.is(".dropdown-menu")){
dropDown.fadeOut('fast');
}
});
答案 1 :(得分:1)
这是一个非常常见的要求。您希望将click
事件绑定到文档,然后查看该点击事件的target
是否在您的菜单中,在这种情况下使用.closest()
:
var dropDown = jQuery('.dropdown-menu');
// Show the menu
jQuery('.menu-nav').click(function () {
dropDown.fadeIn('fast');
});
// Hide the menu
jQuery(document).click(function (e) {
if(!jQuery(e.target).closest('.menu-nav').length || !jQuery(e.target).hasClass('dropdown-menu') {
dropDown.fadeOut('fast');
}
});