使用fadeToggle单击外部关闭div

时间:2013-06-03 09:10:42

标签: jquery toggle fade

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

2 个答案:

答案 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');
    }
});

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

答案 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');
    }
});
相关问题