使用JavaScript单击导航项后,如何折叠导航栏?

时间:2019-03-04 04:26:02

标签: javascript html css bootstrap-4

我正在使用Bootstrap4,但是在单击导航菜单后,它不会折叠,我正在尝试使用Javascript执行此操作。有帮助吗?

<body>
<!--- Navigation -->
<nav class="navbar navbar-expand-lg fixed-top">
    <div class="container-fluid">
      <a class="navbar-brand" href="#"><img src="#"></a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data- 
         target="#navbarResponsive">
        <span class="custom-toggler-icon"><i class="fas fa-bars"></i></span>
      </button>

      <div class="collapse navbar-collapse" id="navbarResponsive">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item">
            <a class="nav-link" href="#home">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#about">About</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#portfolio">Portfolio</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#contact">Contact</a>
          </li>         
        </ul>
      </div>
    </div>
    </nav>

CSS

.navbar {
    padding: .7rem 1rem;
    text-transform: uppercase;
    font-size: .9rem;
    font-weight: 700;
    letter-spacing: .1rem;
    transition: background-color .5s ease 0s;
  background-color: black;
}

.navbar-nav li{
  padding: .8rem;
}
.navbar-nav .nav-link{
  color: white;
  padding-top:.8rem;
}
.navbar-nav .nav-link.active,
.navbar-nav .nav-link:hover{
    color:#c83832;
    transition: ease-in-out .15s;
}


.navbar-toggler{
    color: white;
}

JS

$(document).ready(function() {
  $(document).click(function(event) {
    var clickover = $(event.target);
    var opened = $(".navbar-collapse").hasClass("show");
    if (opened === true && !clickover.hasClass("navbar-toggler")) {
      $(".navbar-toggler").click();
    }
  });
});

0 个答案:

没有答案