汉堡菜单切换Javascript

时间:2019-02-19 15:15:48

标签: javascript jquery html toggle hamburger-menu

我一直在尝试通过汉堡菜单切换创建响应式导航栏。我在网上找到了一个教程吗,并且一切正常,除了菜单的切换。当我单击图标时,什么也没有发生。我对此很陌生,所以我不知道该怎么做。

$(document).ready(function() {
  $('nav-menu').click(function() {
    $('ul').toggleClass('nav-active');
  })
})
.section.menu ul {
  display: none;
}

ul.nav-active {
  display: block !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" />
<div class='section menu'>
  <nav>
    <div class="toggle">
      <i class="fa fa-bars nav-menu" aria-hidden="true"></i>
    </div>
    <ul>
      <li><a href="#jumpcontent">Über Uns</a></li>
      <li><a href="#jumplogin">Login</a></li>
      <li><a href="#jumpfeedback">Referenzen</a></li>
      <li><a href="#jumpcontact">Kontakt</a></li>
    </ul>
  </nav>
</div>

3 个答案:

答案 0 :(得分:2)

您的触发器单击选择器错误。您使用$('nav-menu')意味着jQuery搜索所有<nav-menu></nav-menu>标记,但我认为您要使用nav-menu类,因此应使用$('.nav-menu')

$(document).ready(function() {
    // .nav-menu select tags with the class nav-menu
    // nav-menu select nav-menu tags
    // #nav-menu the tag with the id nav-menu
    $('.nav-menu').click(function() {
        $('ul').toggleClass('nav-active');
        // to check in your console you can do :
        console.log('click triggered on nav-menu');
    });
}

Here is the selectors for jQuery

答案 1 :(得分:0)

您需要使用正确的选择器$('.nav-menu')

$(document).ready(function(){
  $('.nav-menu').click(function(){
    $('ul').toggleClass('nav-active');
  })
})
.section.menu ul {
  display: none;
}

ul.nav-active {
  display: block !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" />
<div class='section menu'>
   <nav>
     <div class="toggle">
       <i class="fa fa-bars nav-menu" aria-hidden="true"></i>
     </div>
     <ul>
       <li><a href="#jumpcontent">Über Uns</a></li>
       <li><a href="#jumplogin">Login</a></li>
       <li><a href="#jumpfeedback">Referenzen</a></li>
       <li><a href="#jumpcontact">Kontakt</a></li>
     </ul>
   </nav>
 </div>

答案 2 :(得分:-2)

<div class='section menu'>
   <nav>
      <div class="toggle">
       <i class="fa fa-bars nav-menu" aria-hidden="true">Toggle Menu</i>
    </div>
   <ul>
   <li><a href="#jumpcontent">Über Uns</a></li>
   <li><a href="#jumplogin">Login</a></li>
   <li><a href="#jumpfeedback">Referenzen</a></li>
   <li><a href="#jumpcontact">Kontakt</a></li>
     </ul>
    </nav>
   </div>

 $(document).ready(function(){
   $('.toggle').click(function(){
  $('ul').toggleClass('nav-active');
 });
 });