如何在点击时隐藏可折叠 Bootstrap 导航栏

How to hide collapsible Bootstrap navbar on click

我使用 Bootstrap 4 创建了这个可折叠的导航栏,效果很好,但我希望它在用户单击 link 时关闭。有什么办法吗?谢谢

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 用于 .icon-bar,因为 Bootstrap 4 不使用图标栏 class.

.navbar-toggler .icon-bar {
  margin: 7px;
  display: block;
  width: 22px;
  height: 1px;
  background-color: #cccccc;
  border-radius: 1px;
}

2021 年更新 - Bootstrap 5(测试版)

使用 javascript 在菜单项上添加点击事件侦听器以关闭折叠导航栏..

const navLinks = document.querySelectorAll('.nav-item')
const menuToggle = document.getElementById('navbarSupportedContent')
const bsCollapse = new bootstrap.Collapse(menuToggle)
navLinks.forEach((l) => {
    l.addEventListener('click', () => { bsCollapse.toggle() })
})

BS5 demo javascript method

或者, 在每个 link 的标记中使用 data-bs-toggledata-bs-target 数据属性来切换折叠导航栏...

<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav me-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Link</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link disabled" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Disabled</a>
                </li>
            </ul>
            <form class="d-flex my-2 my-lg-0">
                <input class="form-control me-sm-2" type="search" placeholder="Search" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>
        </div>
    </div>
</nav>

BS5 demo data-attributes method


2019 年更新 - Bootstrap 4

导航栏变了,但是“点击后关闭”的方法还是一样的:

BS4 demo jQuery method
BS4 demo data-toggle method


Bootstrap 3(原答案)

您可以像这样将 collapse 组件添加到 links..

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

BS3 demo using 'data-toggle' method

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

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

BS3 demo using jQuery method

您可以使用链接上的事件处理程序调用 $.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>

通过尝试上述解决方案,我缺少下拉切换的解决方案,所以给你!同时打开子菜单项。

如果您的切换 class 不同,您可能需要稍微调整一下。

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

我正在使用 ANGULAR,因为它给我带来了问题,routerLink 只需在 li 标签中添加数据切换和目标....或使用 jquery,如 "ZimSystem"

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

我正在使用 Angular 5 和 Bootstrap 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>

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

此代码模拟单击 burguer 按钮,通过单击菜单中的 link 关闭导航栏,保持淡出效果。 angular 的 typescript 解决方案 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>

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

     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>

您可以在单击和关闭时使用简单的绑定,如下所示:(click)="drawer.close()

<a class="nav-link" [routerLink]="navItem.link" routerLinkActive="selected" (click)="drawer.close()">

在您的 TAG 中添加以下代码

data-toggle="collapse" data-target=".navbar-collapse.show"

每个TAG如下所示

<li class="nav-item">
   <a class="nav-link" href="#about-us" data-toggle="collapse" data-target=".navbar-collapse.show">About</a>
</li>

None 上面的答案很有帮助,因为我使用 React Bootstrap。在这种情况下,我必须创建一个状态来存储导航栏是折叠还是展开。

每当我 toggle/click a link.

时,状态就会更新

如果我单击切换菜单本身,就会发生切换

每当我点击 link 时,关闭 就会发生。

这是一个执行相同操作的代码片段:

function Navigation() {
    const [expanded, setExpanded] = useState(false);

    const navToggle = () => {
        setExpanded(expanded ? false : true);
    };

    const closeNav = () => {
        setExpanded(false);
    };

    return (
        <React.Fragment>
            <Navbar expand="lg" expanded={expanded}>
                <Container>
                    <Navbar.Brand as={Link} to="/" onClick={closeNav}>
                        Site Header
                    </Navbar.Brand>
                    <Navbar.Toggle aria-controls="basic-navbar-nav" onClick={navToggle} />
                    <Navbar.Collapse id="basic-navbar-nav">
                        <Nav className="me-auto">
                            <Nav.Link to="/link1" onClick={closeNav}>
                                Link 1
                            </Nav.Link>
                            <Nav.Link to="/link2" onClick={closeNav}>
                                Link 2
                            </Nav.Link>
                            <Nav.Link to="/link3" onClick={closeNav}>
                                Link 3
                            </Nav.Link>
                        </Nav>
                    </Navbar.Collapse>
                </Container>
            </Navbar>
        </React.Fragment>
    );
}

BOOTSTRAP 5

/* FOR MOBILE ONLY */
if (window.matchMedia("(max-width: 991px)").matches) {
  const navLinks = document.querySelectorAll('.nav- 
  item:not(.dropdown)');
  const menuToggle = document.getElementById('navbarToggler');
  const bsCollapse = new bootstrap.Collapse(menuToggle, {toggle: false});
  navLinks.forEach((l) => {
    l.addEventListener('click', () => { bsCollapse.toggle() })
  });
}

设置断点(“navbar-expand-lg”为 991)

在您的 HTML 中:设置 ID、data-bs-target...

对我来说工作很好

在我的例子中,在使用 Zim 的 bootstrap 5 js 解决方案后,菜单始终处于显示状态。 将 toggle: false 添加到 Collapse 对象构造函数后问题得到解决,如 example of the specification.

中所示

Zen的修改代码:

const navLinks = document.querySelectorAll('.nav-item')
const menuToggle = document.getElementById('navbarSupportedContent')
const bsCollapse = new bootstrap.Collapse(menuToggle, {
  toggle: false
})
navLinks.forEach((l) => {
    l.addEventListener('click', () => { bsCollapse.toggle() })
})

(我无法发表评论,所以我创建了一个单独的答案)

我修改了Zim的回答。 现在代码仅在导航栏打开时关闭它。

const navLinks = document.querySelectorAll('.nav-item')
const menuToggle = document.getElementById('navbarSupportedContent')
const bsCollapse = new bootstrap.Collapse(menuToggle, {
  toggle: false
})
navLinks.forEach((l) => {
    l.addEventListener('click', () => {
        if(bsCollapse._isShown()){
            bsCollapse.hide()
        }
    })
})