You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bootstrap中添加切换按钮实现头部折叠功能

折叠切换器实现方案

你当前用的是Bootstrap框架的样式类,实现collapse折叠导航按照以下步骤操作即可:

1. 先确认基础依赖引入

在页面<head>标签内引入Bootstrap CSS,在</body>闭合标签前依次引入Popper.js、Bootstrap JS,三个依赖缺一不可,collapse组件依赖JS逻辑才能运行。

2. 完整修改后的代码

<body>
  <div class="container">
    <header class="blog-header py-3 container">
      <div class="row flex-nowrap justify-content-between align-items-center">
        <div class="col-4 pt-1">
          <a class="text-muted" href="#">Subscribe</a>
        </div>
        <div class="col-4 text-center">
          <a href="#" class="navbar-brand"><img src="2611logo2.png" alt=""></a>
        </div>
        <div class="col-4 d-flex justify-content-end align-items-center">
          <a class="text-muted" href="#">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mx-3"><circle cx="10.5" cy="10.5" r="7.5"></circle><line x1="21" y1="21" x2="15.8" y2="15.8"></line></svg>
          </a>
          <a class="btn btn-sm btn-outline-secondary" href="#">Sign up</a>
          <!-- 新增折叠触发器按钮 -->
          <button class="btn btn-sm btn-outline-secondary ms-2" type="button" data-bs-toggle="collapse" data-bs-target="#navCollapse" aria-expanded="false" aria-controls="navCollapse">
            菜单
          </button>
        </div>
      </div>
    </header>
    <!-- 给原有导航容器加collapse类和对应id -->
    <div class="collapse nav-scroller py-1 mb-2" id="navCollapse">
      <nav class=" nav d-flex justify-content-between">
        <a class="p-2 text-muted" href="#">Shop</a>
        <a class="p-2 text-muted" href="#">T-Shirts</a>
        <a class="p-2 text-muted" href="#">Hoodies</a>
        <a class="p-2 text-muted" href="#">Blog</a>
        <a class="p-2 text-muted" href="#">Bags</a>
        <a class="p-2 text-muted" href="#">Accessoriess</a>
        <a class="p-2 text-muted" href="#">Tracksuit</a>
        <a class="p-2 text-muted" href="#">Shoes</a>
      </nav>
    </div>
  </div>
</body>

3. 版本适配说明

  • 如果你使用的是Bootstrap 4版本,把代码里的data-bs-toggle、data-bs-target的bs-前缀去掉即可,改为data-toggle、data-target
  • 如果需要实现小屏才折叠、大屏默认展开的效果,给折叠容器加上navbar-expand-lg类,将lg替换为你需要的响应式断点即可(sm/md/lg/xl)

内容的提问来源于stack exchange,提问作者Idris Olokunola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:24:02