简体   繁体   中英

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).

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()"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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