简体   繁体   English

单击外部时如何隐藏可折叠导航栏菜单(Bootstrap 5)?

[英]How to hide collapsible navbar menu when clicking outside of it (Bootstrap 5)?

I have a collapsible navbar menu:我有一个可折叠的导航栏菜单:

<div class="collapse navbar-collapse" id="navbarCollapsible">
   .. menu items ..
</div>

I want to hide it whenever a user clicks outside of it (so not just when he clicks the menu button again):我想在用户点击它的外部时隐藏它(所以不仅仅是当他再次点击菜单按钮时):

$(document).ready(function() {
    const navbarCollapsible = document.getElementById('navbarCollapsible');    
    $('.container').on("click", function() {
        navbarCollapsible.hide();
    });
});

But I get: Uncaught TypeError: navbarCollapsible.hide is not a function但我得到: Uncaught TypeError: navbarCollapsible.hide is not a function

Edit:编辑:

I made it work using the following:我使用以下方法使其工作:

$(navbarCollapsible).collapse("hide");

But how can I do it without jQuery?但是没有jQuery怎么办呢?

I know I am using jQuery here, but I know that it's not required for Bootstrap 5 - so how am I supposed to use the hide method as described in the docs without jQuery?我知道我在这里使用 jQuery,但我知道 Bootstrap 5 不需要它 - 那么我应该如何在没有 jQuery 的情况下使用文档中描述的hide方法?

The error is because navbarCollapsible is a element of the DOM and not a jQuery Object. There is no hide available.该错误是因为navbarCollapsible是 DOM 的一个元素,而不是 jQuery Object。没有hide可用。

Try this:试试这个:

$('body').on("click", function() {
  $(navbarCollapsible).hide();
});

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

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