jQuery下拉菜单 - 如何在单击时隐藏菜单

时间:2015-02-19 09:18:52

标签: javascript jquery html css drop-down-menu

我一直在尝试制作它,以便当用户点击时我的导航将隐藏。我只是设法到目前为止,我显然做错了什么。

这是我到目前为止所做的:

没有身体点击 http://jsfiddle.net/yL45ds8j/

尝试瞄准身体(它只是立即隐藏) 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);
        }
    }             
});

有没有人有任何建议我如何解决这个问题?非常感谢

1 个答案:

答案 0 :(得分:2)

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

e.stopPropagation();

小提琴:http://jsfiddle.net/yL45ds8j/8/

这是更清洁的解决方案:jsfiddle.net/yL45ds8j/6