jQuery: triggering close of mobile nav menu

天涯浪子 提交于 2019-12-11 23:13:58

问题


I have an extremely basic jQuery click function that toggles the display of a mobile nav menu-- hamburger-style, triggered by media query-- that is as follows:

// mobile menu click function
$(".mobile-nav-toggle").click(function () {
    $(".mobile-nav-menu").slideToggle();
});

Thus, clicking the .mobile-nav-toggle div triggers the appearance of .mobile-nav-menu which is positioned under a main header bar. My question is-- is there a simple way via jQuery to trigger closing/hiding the menu by clicking/tapping anywhere outside the menu itself? As it stands, one can only close the menu by re-clicking/tapping the toggle button.

Thanks for any insight here.


回答1:


You can have a click handler added to the document itself like

// mobile menu click function
$(".mobile-nav-toggle").click(function() {
  $(".mobile-nav-menu").slideToggle();
});
$(document).click(function(e) {
  //if the click has happend inside the mobile-nav-menu or mobile-nav-toggle then ignore it
  if (!$(e.target).closest('.mobile-nav-menu, .mobile-nav-toggle').length) {
    $(".mobile-nav-menu").slideUp();
  }
})
body {
  min-height: 100px;
  background-color: lightgrey;
}
.mobile-nav-menu {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="mobile-nav-toggle">Toggle</button>
<div class="mobile-nav-menu">menu
  <div>



回答2:


Here is the working code

$(".mobile-nav-toggle").click(function (event) {
    event.stopPropagation();
    $(".mobile-nav-menu").slideToggle();
});

$(document).click( function(){
    $('.mobile-nav-menu').hide();
});


来源:https://stackoverflow.com/questions/26904886/jquery-triggering-close-of-mobile-nav-menu

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