Close hamburger menu after click event

試著忘記壹切 提交于 2019-12-10 18:21:32

问题


I have a hamburger menu which is almost complete with just 1 bug/issue that I can't figure out. My nav links to different areas on the home page. So on the home page the user can click a nav link which would instantly take them down to the desired location on the page.

My issue comes as there is no loading so once the user clicks on the nav link they are brought to the location but the dropdown menu will not close. I tried adding .hide to the JS which hides the dropdown on the click of a link but that created my new issue.

After the user clicks one of the nav links it does hide the menu but upon clicking the menu icon again the menu will not open at all. In dev tools I see that upon clicking one of the nav links it is given the style of display:none so I feel that the issue might lie there. Thanks for the help and please let me know if any other information is needed!

HTML:

     <nav class="navbar navbar-light navbar-fixed-top">
     <div class="wrapping container-fluid">
        <div class="hamburger">
          <div class="line"></div>
          <div class="line"></div>
          <div class="line"></div>
        </div>
      <ul class="nav navbar-nav float-sm-right mr-0 menu">
        <li class="nav-item">
          <span class="sr-only"></span>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#schedule">Schedule<span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#workshops">Workshops</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#locations">Location</a>
        </li>
        <li class="nav-item">
          <a class="nav-link last-link" href="#register">Register</a>
        </li>
      </ul>
      <a class="navbar-brand" href="#home"><img class="logo" src="img/Logo.png" alt=""></a>
    </div>
  </nav>

CSS for this menu:

.menu{
  height: 0;
  overflow: hidden;
  transition: height 0.3s;
}

.open{
  height: 295px;
}

.hamburger {
  cursor: pointer;
  padding: 15px 10px 15px 0;
  display: block;
  float: right;
  margin-top: 15px;
}

JS:

$('.hamburger').on('click', function () {

$('.menu').toggleClass('open');

});

$( '.menu a' ).on("click", function(){
$('.menu').hide();
});

回答1:


If you're going to use .toggleClass('open') to open the menu, use it for closing the menu as well.

Generally, though, you'll want to use .addClass() and .removeClass() instead:

$('.hamburger').on('click', function () {
  $('.menu').addClass('open');
});

$( '.menu a' ).on("click", function(){
  $('.menu').removeClass('open');
});


来源:https://stackoverflow.com/questions/41641333/close-hamburger-menu-after-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!