2

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吗?

4

2 回答 2

2

将事件处理程序附加clickdocument. 当点击发生时,检查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/

于 2013-06-03T09:18:02.500 回答
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');
    }
});
于 2013-06-03T09:19:37.380 回答