jQuery 向下滑动菜单 - 如何在 body 单击时隐藏菜单

jQuery slide down menu - how to hide menu on body click

我一直在努力让我的导航在用户点击关闭时隐藏。我只做到了这么远,显然我做错了什么。

这是我目前拥有的:

没有body点击 http://jsfiddle.net/yL45ds8j/

正在尝试 body 点击(只是立即隐藏) http://jsfiddle.net/yL45ds8j/1/

代码:

function handler1() {
    $('.headnav').addClass('open').animate({
        top: "0"
    },400);            
    $(this).addClass('open');
    $(this).one("click", handler2);
}
function handler2() {
    $('.headnav').removeClass('open').animate({
        top: "-100%"
    },400);
    $('.menuBtn').removeClass('open');
    $('.menuBtn').one("click", handler1);
}             

$(".menuBtn").one("click", handler1);

$('body').click(function(event) { 
    if(!$(event.target).closest('.headnav.open').length) {
        if($('.headnav').hasClass("open")) {
            $('.headnav').removeClass('open').animate({
                top: "-100%"
            },400);
        }
    }             
});

有人对我如何解决这个问题有什么建议吗?非常感谢

menuBtn的click事件冒泡到body,body的click事件处理函数关闭。请停止在 menuBtn 处理程序中传播事件。

e.stopPropagation();

Fiddle: http://jsfiddle.net/yL45ds8j/8/

这是更简洁的解决方案:jsfiddle。net/yL45ds8j/6