2014-01-22 101 views
1

我想写一个简单的jquery函数来添加类到我的HTML为屏幕nav过渡。我可以很容易地通过使用.toggleClass来做到这一点,但我想要使用if语句,如果nav单击正文(除nav之外的任何内容)将会再次隐藏它。我建立了demo codepen。任何人都可以让我知道我要去哪里吗?jQuery关屏幕导航

回答

2
$('body !nav') 

不是一个有效的选择器。你应该做的是给文档添加一个监听器:

$(document).click(function() { 
    // Stuff you want to do on a click 
}); 

这将捕获所有不被另一个函数处理的点击。然后,捕获发生在资产净值的点击次数:

$("nav").click(function(e) { 
    // Stuff that should happen when nav is clicked. 
    e.stopPropagation(); 
}); 
2

两件事情需要解决:

1)在导航点击使用stopPropagation()Documentation),以避免注册体点击(事件的冒泡默认值):

$('nav').click(function(e) { 
    e.stopPropagation(); 
}); 

2)使用:not选择器(Documentation):

$('body:not(nav)').click(function(e) { 
    if($('nav').hasClass('active')){ 
     $('nav, #wrapper').removeClass('active'); 
    } 
}); 

Updated Code Pen

0

试试这个:

$('a#menu').click(function(e) { 
    e.preventDefault(); 
    e.stopPropagation(); 
    //this should just be .addClass but to demonstrate functionality I've left it as .toggleClass 
    $('nav, #wrapper').toggleClass('active'); 


}); 


//how I want it to work 

//on click of anything besides nav, if the active class is on the nav, take off the active class 
$('body:not(nav)').click(function(e) { 

    if($('nav').hasClass('active')){ 
    $('nav, #wrapper').removeClass('active'); 
    } 

});