我使用Bootstrap 4创建了这个可折叠的导航栏,效果很好,但我想在用户点击链接时关闭它。有什么办法吗?谢谢
html导航栏:
<nav class="navbar navbar-toggleable-md fixed-top"> <button id="nav-btn"class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarDiv" aria-expanded="false" aria-label="Toggle navigation"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <div class="container"> <a class="navbar-brand" href="#"><img src="Images/logo.png" width="60px"></a> <div class="collapse navbar-collapse" id="navbarDiv"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#home">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#about-us">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#pricing">Pricing</a> </li> </ul> </div> </div> </nav>
css for .icon-bar,因为Bootstrap 4不使用icon-bar类。
.navbar-toggler .icon-bar { margin: 7px; display: block; width: 22px; height: 1px; background-color: #cccccc; border-radius: 1px; }
解决方法
您可以将折叠组件添加到此类链接中。
<ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#home" data-toggle="collapse" data-target=".navbar-collapse.show">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#about-us" data-toggle="collapse" data-target=".navbar-collapse.show">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#pricing" data-toggle="collapse" data-target=".navbar-collapse.show">Pricing</a> </li> </ul>
Demo using ‘data-toggle’ method
或者,(也许是一种更好的方式)使用像这样的jQuery ..
$('.navbar-nav>li>a').on('click',function(){ $('.navbar-collapse').collapse('hide'); });
更新2018 Bootstrap 4.0.0