如何在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
相关产品推荐
相关产品推荐

