使用fadeToggle在外部单击以关闭div



我正在使用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中可能吗?

将事件处理程序附加到document上的click事件。当点击发生时,检查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');
    }
});

工作示例:http://jsfiddle.net/UJNd5/

这是一个非常常见的需求。您想将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');
    }
});

最新更新