在Booststrap 4中单击外部时关闭打开的折叠导航栏

时间:2017-01-05 21:18:04

标签: twitter-bootstrap bootstrap-4 twitter-bootstrap-4

我目前正在使用Bootstrap 4,我想在外面点击时关闭折叠的导航栏。它只能在您单击切换按钮时关闭。

此外,当我点击切换按钮时,导航链接出现问题。打开后,导航链接正在反弹。我无法弄清楚原因。请有人帮我解决我的问题。谢谢!

这是我的代码:

<body>
 <!--  start navbar -->
 <nav class="navbar navbar-light bg-faded navbar-fixed-top">
  <button class="navbar-toggler hidden-lg-up float-xs-right" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"></button>
    <a class="navbar-brand" href="#"></a>

    <div class="collapse navbar-toggleable-md" id="main-navbar">
      <ul class="nav navbar-nav float-lg-right">
        <li class="nav-item">
          <a class="nav-link" href="#home">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#section-about">About</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#section-portfolio">Portfolio</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#section-contact">Contact</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#resume">Resume</a>
        </li>
      </ul>
    </div>
  </nav>
  <!--   end navbar -->
</body>

这是我的代码链接:

http://codepen.io/marcvs/pen/jVONGM

2 个答案:

答案 0 :(得分:2)

以下是您问题的解决方案:

$(document).ready(function () {
    $(document).click(function (event) {
        var clickover = $(event.target);
        var _opened = $(".collapse").hasClass("collapse in");

        if (_opened === true && !clickover.hasClass("navbar-toggler")) {
            $("button.navbar-toggler").click();
        }
    });
});

Codepen:http://codepen.io/anon/pen/xgbmqr

它是this answer

的修改版本

答案 1 :(得分:0)

我知道这是一个古老的话题,但是我偶然发现了这个问题,并认为我可以稍微更新一下解决方案:

$(document).click(event => {
  const isNavbarOpened = $("#navbar.navbar-collapse").hasClass("collapse show");

  // this way, if the navbar is not opened, we don't perform unnecessary operations
  if (isNavbarOpened) {
    const clickedElement = $(event.target);
    const clickedInsideNavbar = clickedElement.closest('nav.navbar').length > 0;

    if (!clickedInsideNavbar) {
      $("button.navbar-toggler").click();
    }
  }
});