问题
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