简体   繁体   English

当我在菜单外单击时如何隐藏jQuery toggle()?

[英]How to hide jQuery toggle() when I click outside of the menu?

I have found a couple topics regarding to this issue, but none of them unfortunately worked out for me. 我发现了与此问题有关的几个主题,但不幸的是,没有一个主题对我有用。 I am using this jQuery method like this: 我正在使用这样的jQuery方法:

//jQuery
$('.menu_user').click(function(){
    $(".top_menu").toggle();
});
// HTML
<div class="menu_user">MENU</div>
<nav class="top_menu">
  ...
</nav>

Basically, when I click on the MENU div, the menu is rolled down, when I click on it again, then the menu is rolled up = hidden. 基本上,当我单击MENU div时,菜单将向下滚动,当我再次单击它时,菜单将向上滚动=隐藏。 The problem is that when the menu is rolled down and I click outside the Menu div, the menu stays displayed - and I would like to hide it. 问题在于,当菜单向下滚动并在Menu div之外单击时,菜单保持显示状态-我想将其隐藏。

I went through some tutorials, but I didn't find a solution that would solve this issue. 我浏览了一些教程,但是没有找到可以解决此问题的解决方案。

I'll be glad for every help regarding to this issue. 对于这个问题的所有帮助,我都会很高兴。

Thanks! 谢谢!

You could use 你可以用

$(document).on( "click", function() {

    if ($('.top_menu:hover').length === 0) {
        //hide the stuff
        //roll up menu
         $(".top_menu").hide();
    } else if ($('.menu_user:hover').length === 0) {
         $(".top_menu").toggle();
    }

});

so that when the menu is rolled down and the user clicked outside .top_menu it will roll up .top_menu 因此,当菜单向下滚动并且用户在.top_menu之外.top_menu ,它将向上滚动.top_menu

Remember that the above code will fire every time a user clicks on the page. 请记住 ,上面的代码将在用户每次单击页面时触发。

You can do a click event, and inside it check if the click was inside the menu_user div. 您可以单击事件,然后在其中检查单击是否在menu_user div中。 If not, then you can hide the dropdown. 如果不是,则可以隐藏下拉菜单。

$("body > div").click(function() {
    if ($(this).attr("class") != "menu_user") {
       $(".top_menu").hide();
    }
});

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

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