jQuery:触发移动导航菜单的关闭 [英] jQuery: triggering close of mobile nav menu

查看:86
本文介绍了jQuery:触发移动导航菜单的关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常基本的jQuery click函数,可切换移动导航菜单的显示方式(汉堡式,由媒体查询触发),如下所示:

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();
});

因此,单击.mobile-nav-toggle div会触发.mobile-nav-menu的外观,该外观位于主标题栏下方.我的问题是-是否有一种简单的方法通过jQuery来触发关闭/隐藏菜单,方法是单击/点击菜单本身 outside 之外的任意位置?就目前而言,只能通过重新单击/点击切换按钮来关闭菜单.

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.

感谢您的任何见解.

推荐答案

您可以将点击处理程序添加到文档本身中,例如

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>

这篇关于jQuery:触发移动导航菜单的关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆