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

前端之家收集整理的这篇文章主要介绍了html – 如何在点击时隐藏可折叠的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>

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');
});

Demo using jQuery method

更新2018 Bootstrap 4.0.0

导航栏已更改,但关闭后的单击方法仍然相同:

https://www.codeply.com/go/nFDHoEqqJQ

原文链接:https://www.f2er.com/html/232549.html

猜你在找的HTML相关文章