简体   繁体   中英

Bootstrap 3 close nav menu when you click outside

I am using the following jQuery:

            jQuery(document).click(function (event) {
               var clickover = jQuery(event.target);
               var _opened = jQuery(".navbar-collapse2").hasClass("in");
               if (_opened === true && !clickover.hasClass("navbar-toggle")) {
                  jQuery("button.navbar-toggle").click();
               }
            });

The problem is within navbar-collapse I have some sub menus and when I click to expand/collapse them. It also collapses the main nav menu.

You should probably check if your clicked element is not a child of .navbar-toggle . You can do that with the closest() function. This will find the first parent that matches the selector.

if (_opened === true && !clickover.hasClass("navbar-toggle") && clickover.closest(".navbar-toggle").length === 0)

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