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

Bootstrap navbar导航菜单如何实现点击跳转后保持标签高亮

解决方案

问题根因

Bootstrap导航的激活高亮需要给对应链接手动添加.active类标识,多页面跳转后DOM会重新渲染,无法自动保留状态,需要结合样式和状态标记实现。

步骤1:调整CSS规则

把你现有CSS修改为同时匹配hover和active状态,保证激活时和悬浮样式一致:

#nav li a:hover,
#nav li a.active,
#nav li a.dropdown-toggle.show {
  background-color: #87CEEB;
}
/* 下拉菜单激活项补充样式,可按需调整文字颜色 */
#nav .dropdown-item.active {
  background-color: #87CEEB;
  color: #000;
}

步骤2:给当前页导航添加active类,两种方案可选

  • 方案1:PHP多页手动标记(兼容性最好)
    每个页面对应的导航<a>标签上添加active类即可,示例:
    首页index.php的导航项修改为 <a class="nav-link active" href="index.php">Accueil</a>
    如果是下拉菜单的子页面,除了子项加active,还需要给父级dropdown-toggle添加active show类,保证父级导航也高亮。
  • 方案2:JS自动匹配(无需逐个页面修改)
    将以下代码添加到所有页面的公共尾部,脚本会自动识别当前URL,给对应导航添加激活状态:
const currentPath = window.location.pathname.split('/').pop();
document.querySelectorAll('#nav .nav-link, #nav .dropdown-item').forEach(link => {
  const linkPath = link.getAttribute('href').split('/').pop();
  if (linkPath === currentPath) {
    link.classList.add('active');
    if (link.classList.contains('dropdown-item')) {
      link.closest('.dropdown').querySelector('.dropdown-toggle').classList.add('active', 'show');
    }
  }
});

额外兼容性修复提示

你当前使用的是Bootstrap 5版本,旧版的data-toggle属性不兼容,需要将下拉菜单触发属性改为data-bs-toggle,否则下拉功能可能失效,修改后代码如下:

<a class="nav-link dropdown-toggle" data-bs-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Bulletins</a>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 11:27:03