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

如何为自定义Bootstrap导航栏添加CSS类并高亮当前点击菜单项

解决Bootstrap导航栏添加自定义active类的问题

嘿,我来帮你搞定这个导航栏active类的问题!针对你用Bootstrap 3+jQuery的场景,我整理了覆盖页面加载自动匹配、点击切换两种需求的解决方案:

第一步:确认导航栏HTML结构

先确保你的导航项结构大概是这样(如果不是,调整代码里的选择器即可):

<nav class="navbar navbar-default">
  <div class="container">
    <ul class="nav navbar-nav">
      <li class="menu__item"><a href="/index.html">首页</a></li>
      <li class="menu__item"><a href="/about.html">关于我们</a></li>
      <li class="menu__item"><a href="/services.html">服务</a></li>
    </ul>
  </div>
</nav>

第二步:添加jQuery逻辑

把这段代码放在页面底部(你已经引入jQuery和Bootstrap JS之后),它会完成两个核心操作:

  1. 页面加载时自动给当前页面对应的菜单项加上menu__item--current类
  2. 点击菜单项时,移除其他项的类并给当前点击项添加类
$(document).ready(function() {
  // 页面加载时匹配当前URL添加自定义active类
  var currentPath = window.location.pathname;
  // 处理根目录首页的特殊情况(比如首页路径是/)
  if (currentPath === '/') {
    currentPath = '/index.html';
  }
  $('.menu__item a').each(function() {
    var linkPath = $(this).attr('href');
    // 匹配路径(如果是绝对路径,可调整为$(this).attr('href').includes(currentPath))
    if (currentPath.includes(linkPath)) {
      $(this).parent('.menu__item').addClass('menu__item--current');
      // 若需要保留Bootstrap自带的active类,可添加这行:
      // $(this).parent('.menu__item').addClass('active');
    }
  });

  // 点击菜单项时切换自定义active类
  $('.menu__item a').click(function(e) {
    // 移除所有菜单项的自定义active类
    $('.menu__item').removeClass('menu__item--current');
    // 给当前点击项的父元素添加类
    $(this).parent('.menu__item').addClass('menu__item--current');
    // 若需要保留Bootstrap自带的active类,可添加这两行:
    // $('.menu__item').removeClass('active');
    // $(this).parent('.menu__item').addClass('active');
  });
});

可选的细节调整

  • 如果你的导航项href是绝对路径(比如https://xxx.com/about.html),把路径匹配条件改成$(this).attr('href').includes(currentPath)即可
  • 如果自定义类需要加在<a>标签而非<li>上,把代码里的.parent('.menu__item')替换成$(this)
  • 记得给menu__item--current添加CSS样式,确保视觉上能区分当前项:
.menu__item--current a {
  color: #fff !important;
  background-color: #337ab7 !important; /* 可与Bootstrap主题色保持一致 */
}

这样就能顺利给选中的菜单项加上自定义active类啦!

内容的提问来源于stack exchange,提问作者Shoyeb Athar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:12:47