简体   繁体   English

在外部单击时如何关闭响应式Bootstrap 4菜单

[英]How to close responsive bootstrap 4 menu when clicking outside

On desktop, clicking outside of my bootstrap nav menu closes it. 在桌面上,在我的引导导航菜单之外单击以将其关闭。 However this behaviour does not work on mobile. 但是,此行为不适用于移动设备。

I've tried to edit some code from a codepen to reference the relevant classes on my website, to no avail. 我试图从代码库中编辑一些代码以引用我网站上的相关类,但无济于事。

Here is the code I've used: 这是我使用的代码:

const $menu = $('#id-of-menu');

$(document).mouseup(e => {
   if (!$menu.is(e.target) // if the target of the click isn't the container...
   && $menu.has(e.target).length === 0) // ... nor a descendant of the container
   {
     $menu.removeClass('show');
  }
 });

I'd hoped that clicking outside the menu would remove the 'show' class from the menu, thereby hiding it. 我希望在菜单外单击可以从菜单中删除“显示”类,从而将其隐藏。 In practice though, nothing happens. 但是实际上,什么也没有发生。

SOLUTION

The answer provided here by Henrywright solved my problem (obviously after changing relevant class and id names). 亨利赖特在这里提供的答案解决了我的问题(显然是在更改了相关的类和ID名称之后)。

This is the eventual code I used: 这是我最终使用的代码:

jQuery('body').bind('click', function(e) {
    if(jQuery(e.target).closest('.navbar').length == 0) {
        // click happened outside of .navbar, so hide
        var opened = jQuery('#id-of-menu').hasClass('show');
        if ( opened === true ) {
            jQuery('#id-of-menu').collapse('hide');
        }
    }
});

移动设备上不存在“ mouseup”事件,请尝试“单击”

function onMenuClick(){
    $('#id-of-menu').collapse('hide');
}

Add this in your menu items: 在您的菜单项中添加:

onclick="onMenuClick()"

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

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