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

当URL部分匹配菜单项时为导航添加active类的实现方法

嘿,我来帮你搞定这个导航高亮的问题!当页面URL匹配菜单链接时给对应项加active类,这里有几种实用的解决方案:

纯JavaScript实现(无依赖)

这是最通用的方法,不需要任何框架,直接在页面加载后运行即可:

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
  // 获取当前页面的路径(去掉域名,只保留路径部分)
  const currentPath = window.location.pathname;
  // 获取所有导航链接元素
  const navLinks = document.querySelectorAll('.wrapper ul li a');

  // 遍历每个导航链接
  navLinks.forEach(link => {
    const linkPath = link.getAttribute('href');
    // 统一处理末尾斜杠,避免匹配失败
    const cleanedCurrentPath = currentPath.replace(/\/$/, '');
    const cleanedLinkPath = linkPath.replace(/\/$/, '');

    // 判断当前路径是否以链接路径开头(适合父菜单高亮子页面的场景)
    if (cleanedCurrentPath.startsWith(cleanedLinkPath)) {
      // 给父元素<li>添加active类,也可以直接给<a>加,看你的样式需求
      link.parentElement.classList.add('active');
    }
  });
});
jQuery实现(如果你项目在用jQuery)

如果你的项目已经引入了jQuery,代码会更简洁:

$(document).ready(function() {
  const cleanedCurrentPath = window.location.pathname.replace(/\/$/, '');
  
  $('.wrapper ul li a').each(function() {
    const cleanedLinkPath = $(this).attr('href').replace(/\/$/, '');
    if (cleanedCurrentPath.startsWith(cleanedLinkPath)) {
      $(this).parent().addClass('active');
    }
  });
});
关键注意事项
  • 处理末尾斜杠:统一去掉路径末尾的斜杠,避免因为/en/blogs/和/en/blogs这种细微差异导致匹配失败
  • 匹配规则选择:
    • 用startsWith:只匹配以链接路径开头的URL,完美适配父菜单高亮子页面的场景(比如/en/blogs/xxx匹配/en/blogs/)
    • 若需要更宽松的匹配,可换成includes,但要注意相似路径的误匹配问题
  • 样式定义:别忘了在CSS里给active类设置高亮样式,比如:
.wrapper ul li.active a {
  color: #2563eb; /* 示例蓝色 */
  font-weight: bold;
  border-bottom: 2px solid #2563eb;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:33:21