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


108

我已经使用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;
}

Answers:


170

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

演示使用jQuery方法

更新2019-Bootstrap 4

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

https://codeply.com/go/nFDHoEqqJQ(jQuery方法)
https://codeply.com/go/PqIBtz3HPLdata-toggle方法,请参阅Bootstrap 折叠组件


1
嗨,谢谢您的答复,但是当我这样做时,它不会折叠导航栏,而是将它与scrollspy链接到div元素。有什么建议?谢谢
Rudi Thiel

3
太好了,记住您可以<span class="navbar-toggler-icon"></span>在BS 4中使用图标栏
。– Zim

2
您可以navbar-inverse
Zim

3
@Zim-必须将data-toggle和设置data-target为父元素(li),否则,scrollspy将不起作用。也许您应该编辑答案。:)
J. Sadi

1
@ J.Sadi的建议为我完成了这项工作。否则,链接点击没有任何作用。
totalhack

44

我使用的是ANGULAR,因为它给我带来了问题,所以routerLink只是在li标记中添加了数据切换和目标....或使用诸如“ ZimSystem”的jquery

<div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item" data-toggle="collapse" data-target=".navbar-collapse.show">
          <a class="nav-link" routerLink="/inicio" routerLinkActive="active" >Inicio</a>
        </li>
      </ul>
</div>


4
谢谢,您为我节省了一天!我正在使用Angular 6和Bootstrap 4.1.3。适用data-toggle="collapse" data-target=".navbar-collapse.show"于li包括下拉菜单li。
学习中…

2
这个答案是干净极了!
国家Chirara

17

您可以$.collapse('hide');在链接上使用事件处理程序进行调用。

$('.nav-link').on('click',function() {
  $('.navbar-collapse').collapse('hide');
});
.navbar-toggler .icon-bar {
  margin: 7px;
  display: block;
  width: 22px;
  height: 1px;
  background-color: #cccccc;
  border-radius: 1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<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>


9

通过尝试上述解决方案,我错过了Dropdown切换的解决方案,因此您可以开始!同时打开子菜单项。

如果您的切换类不同,也许您需要稍微调整一下。

$('.navbar-nav li a').on('click', function(){
    if(!$( this ).hasClass('dropdown-toggle')){
        $('.navbar-collapse').collapse('hide');
    }
});

1
它更短,甚至可能更快:$(".navbar-nav li a:not('.dropdown-toggle')") .on('click', function () { $('.navbar-collapse').collapse('hide'); }
James Wilkins

5

这是单击锚点然后在列表项中应用此行时关闭菜单的解决方案

     data-target="#sidenav-collapse-main" data-toggle="collapse"

为我工作的真正例子如下

      <li class="nav-item" data-target="#sidenav-collapse-main" data- 
      toggle="collapse" >
      <a class="nav-link" routerLinkActive="active" routerLink="/admin/users">
        <i class="ni ni-single-02  text-orange"></i> Users
      </a>
      </li>

2

我将Angular 5与Boostrap 4一起使用。它以这种方式对我有效。

 $(document).on('click', '.navbar-nav>li>a, .navbar-brand, .dropdown-menu>a', function (e) {
      if ( $(e.target).is('a') && $(e.target).attr('class') != 'nav-link dropdown-toggle' ) {
        $('.navbar-collapse').collapse('hide');
      }
    });
   }
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
  <a class="navbar-brand" [routerLink]="['/home']">FbShareTool</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation" style="">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarColor01">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active" *ngIf="_myAuthService.isAuthenticated()">
        <a class="nav-link" [routerLink]="['/dashboard']">Dashboard <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item dropdown" *ngIf="_myAuthService.isAuthenticated()">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Manage
          </a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">
            <a class="dropdown-item" [routerLink]="['/fbgroup']">Facebook Group</a>
            <div class="dropdown-divider"></div>
            <a class="dropdown-item" href="#">Fetch Data</a>
          </div>
      </li>
    </ul>

    <ul class="navbar-nav navbar-right navbar-right-link">
        <li class="nav-item" *ngIf="!_myAuthService.isAuthenticated()" >
            <a class="nav-link" (click)="logIn()">Login</a>
        </li>
        <li class="nav-item" *ngIf="_myAuthService.isAuthenticated()">
           <a class="nav-link">{{ _myAuthService.userDetails.displayName }}</a>
        </li>
        <li class="nav-item" *ngIf="_myAuthService.isAuthenticated() && _myAuthService.userDetails.photoURL">
            <a>
              <img [src]="_myAuthService.userDetails.photoURL" alt="profile-photo" class="img-fluid rounded" width="40px;">
            </a>
        </li>
        <li class="nav-item" *ngIf="_myAuthService.isAuthenticated()">
            <a class="nav-link" (click)="logOut()">Logout</a>
        </li>
    </ul>

  </div>
</nav>


2

仅使用Angular 2/4模板而不进行编码的最简单方法是:

<nav class="navbar navbar-default" aria-expanded="false">
  <div class="container-wrapper">

    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" (click)="isCollapsed = !isCollapsed">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

    <div class="navbar-collapse collapse no-transition" [attr.aria-expanded]="!isCollapsed" [ngClass]="{collapse: isCollapsed}">
      <ul class="nav navbar-nav" (click)="isCollapsed = !isCollapsed">
        <li [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact: true}"><a routerLink="/">Home</a></li>
        <li [routerLinkActive]="['active']"><a routerLink="/about">About</a></li>
        <li [routerLinkActive]="['active']"><a routerLink="/portfolio">Portfolio</a></li>
        <li [routerLinkActive]="['active']"><a routerLink="/contacts">Contacts</a></li>
      </ul>
    </div>

  </div>
</nav>

2

此代码模拟单击burguer按钮以通过单击菜单中的链接来关闭导航栏,从而保持淡出效果。带有打字稿的角度7解决方案。避免routerLink问题。

ToggleNavBar () {
    let element: HTMLElement = document.getElementsByClassName( 'navbar-toggler' )[ 0 ] as HTMLElement;
    if ( element.getAttribute( 'aria-expanded' ) == 'true' ) {
        element.click();
    }
}

<li class="nav-item" [routerLinkActive]="['active']">
    <a class="nav-link" [routerLink]="['link1']" title="link1" (click)="ToggleNavBar()">link1</a>
</li>

用jQuery提出的解决方案不能在Angular 7中大量加载时正常工作。
埃杜

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.