简体   繁体   English

在元素外部单击而不尝试导航按钮时,试图关闭移动菜单(正在删除类)

[英]Trying to close mobile menu (removing class) when clicking outside of element without effecting nav button

I'm really struggling to make this work. 我真的很努力使这项工作。 I have a mobile menu that opens on clicking the button in the header. 我有一个移动菜单,单击标题中的按钮会打开。 This adds an active class to the menu to display it. 这会将活动类添加到菜单中以显示它。 I have made it full width and locked scrolling. 我已经将其设置为全角并锁定了滚动。 But I want it to close when clicking outside the menu, (removing the class) but I can't get it to work. 但是我想在菜单外单击(关闭类)时将其关闭,但无法正常工作。

This is what I've tried: 这是我尝试过的:

<script> 
jQuery(document).click(function(event) { 
if(!jQuery(event.target).closest('.navgrid .site__header--mobilenav, .burgerbox').length) {
    if(jQuery('#mobilenavcontainer').hasClass('site__header--mobilenav-active')){
    jQuery('jQuery').removeClass('site__header--mobilenav-active')
}

}        
}); 
</script>

But it doesn't seem to work... 但这似乎不起作用...

A simple example but I think covering your requirements. 一个简单的例子,但我认为可以满足您的要求。 The button shows the menu. 该按钮显示菜单。 Click at any place outside the menu to hide it. 在菜单外的任何位置单击以将其隐藏。

 $(document).mouseup(function(e) { const container = $(".menu"); /* Assign outside which element must be clicked */ if (!container.is(e.target) && container.has(e.target).length === 0) { $(".menu").css("display", "none"); } }); $("body").on("click", "button", function() { $(".menu").css("display", "flex"); }); 
 ul { list-style: none; width: 100%; padding: 0; margin: 0; flex-flow: column wrap; display: none; } li { background-color: lightblue; border: thin solid gray; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>Click me</button> <ul class="menu"> <li>Option 1</li> <li>Option 1</li> <li>Option 1</li> </ul> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM