【问题标题】:Adding code to existing .js to collapse navbar when click outside menu单击外部菜单时,将代码添加到现有 .js 以折叠导航栏
【发布时间】:2019-07-30 05:50:03
【问题描述】:

目前我在 Bootstrap 4.1.3 中使用 .js 作为我的粘性导航栏,它可以按需要工作。我曾尝试在脚本中插入一个函数,如果您在菜单外单击,它会使手机上的导航栏崩溃。然而,没有运气。 https://biogenity.com/RC19/index.html

我目前使用的代码是:

        $(document).ready(function () {
            var stickyToggle = function (sticky, stickyWrapper, scrollElement) {
                var stickyHeight = sticky.outerHeight();
                var stickyTop = stickyWrapper.offset().top;
                if (scrollElement.scrollTop() >= stickyTop) {
                    stickyWrapper.height(stickyHeight);
                    sticky.addClass("is-sticky");
                }
                else {
                    sticky.removeClass("is-sticky");
                    stickyWrapper.height('auto');
                }
            };

            $('[data-toggle="sticky-onscroll"]').each(function () {
                var sticky = $(this);
                var stickyWrapper = $('<div>').addClass('sticky-wrapper'); 
                sticky.before(stickyWrapper);
                sticky.addClass('sticky');

                $(window).on('scroll.sticky-onscroll resize.sticky-onscroll', function () {
                    stickyToggle(sticky, stickyWrapper, $(this));
                });

                stickyToggle(sticky, stickyWrapper, $(window));
            });             
        });

我希望能够实现如下类似的功能。不确定这是否是“在菜单外单击时折叠”的最佳解决方案。

        $(document).on('click', function(event){
          var $clickedOn = $(event.target),
              $collapsableItems = $('.collapse'),
              isToggleButton = ($clickedOn.closest('.navbar-toggle').length == 1),
              isLink = ($clickedOn.closest('a').length == 1),
              isOutsideNavbar = ($clickedOn.parents('.navbar').length == 0);

          if( (!isToggleButton && isLink) || isOutsideNavbar ) {
            $collapsableItems.each(function(){
              $(this).collapse('hide');
            });
          }
        });

提前致谢。

【问题讨论】:

    标签: javascript bootstrap-4 navbar collapse


    【解决方案1】:

    根据您的代码,试试这个:

    $(document).click(function (event) {
      var clickedOn = $(event.target),
        isNavbar = clickedOn.hasClass('navbar'),
        // Target only nav links not all links
        isNavbarLink = clickedOn.closest('.nav-link').length == 1,
        navbarCollapse = $('.navbar-collapse'),
        isNavbarOpen = navbarCollapse.hasClass('show');
    
      // if its not navbar and navbar is opened
      if (!isNavbar && isNavbarOpen) {
        // if the user is not cliking on the nav links
        if (!isNavbarLink) {
          // thes close the navbar 
          navbarCollapse.collapse('hide');
        }
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2016-02-22
      • 2018-08-23
      • 2018-05-27
      • 2014-12-24
      • 2018-04-18
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多