如何在单击时隐藏可折叠的Bootstrap 4导航栏

我使用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>

.icon-bar的css,因为Bootstrap 4不使用icon-bar类。

.navbar-toggler .icon-bar {

margin: 7px;

display: block;

width: 22px;

height: 1px;

background-color: #cccccc;

border-radius: 1px;

}

回答:

您可以collapse像这样将组件添加到链接。

<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>

,(也许是一种更好的方法)像这样使用jQuery。

$('.navbar-nav>li>a').on('click', function(){

$('.navbar-collapse').collapse('hide');

});

以上是 如何在单击时隐藏可折叠的Bootstrap 4导航栏 的全部内容, 来源链接: utcz.com/qa/415056.html

回到顶部