
通过 javascript 在页面加载时解析当前 url,遍历侧边栏所有导航链接,匹配 `href` 并为对应项动态添加 `active` 类,实现菜单项自动激活。
在基于 Metrical Dashboard(一个轻量、bootstrap 5 驱动的管理仪表盘模板)开发时,常需让左侧导航栏(.nav-item a)根据当前访问路径自动高亮。你提供的代码逻辑方向正确,但存在两个关键问题:
- window.location 是一个 Location 对象,而 a.href 返回的是完整绝对 URL 字符串,直接用 == 比较对象与字符串会恒为 false;
- 使用 Filter() 创建新数组再取 [0] 虽可行,但不如原生循环清晰高效,且未处理路径匹配的容错性(如带查询参数、末尾斜杠差异等)。
✅ 推荐写法(兼容性强、语义清晰):
document.addEventListener('DOMContentLoaded', function () { const currentPath = window.location.pathname; // 获取纯净路径,如 '/dashboard' 或 '/users/list' const navLinks = document.querySelectorAll('.nav-item a'); navLinks.forEach(link => { const linkPath = new URL(link.href).pathname; // 安全提取 href 的 pathname if (linkPath === currentPath || (currentPath !== '/' && linkPath === currentPath + '/') || (currentPath === '/' && linkPath === '/index.html')) { link.classlist.add('active'); // 可选:向上追溯 .nav-item 父级并加 active(适配部分主题结构) link.closest('.nav-item')?.classList.add('active'); } else { link.classList.remove('active'); link.closest('.nav-item')?.classList.remove('active'); } }); });
? 关键说明与注意事项:
- ✅ 使用 window.location.pathname 替代 window.location,确保只比对路径部分,避免协议、域名、查询参数干扰;
- ✅ 用 new URL(link.href).pathname 统一提取 标签的路径,兼容相对路径(如 users/)和绝对路径(如 /reports);
- ✅ 增加了常见路径变体判断(如 /settings vs /settings/),提升鲁棒性;
- ✅ 添加 domContentLoaded 事件包裹,确保 DOM 加载完成后再执行,避免节点未就绪;
- ⚠️ 若项目使用前端路由(如 history API 或 Hash 模式),需改用 window.location.hash 或监听 popstate 事件;
- ⚠️ Metrical 默认未为 .nav-item 添加 active 类,若需父容器高亮(如展开子菜单),请同步操作 closest(‘.nav-item’)。
? 进阶提示:
如需支持「模糊匹配」(例如 /user/123 应激活 /user 菜单项),可将 === 替换为 currentPath.startsWith(linkPath),并确保 linkPath 以 / 结尾(如 linkPath = linkPath.replace(//?$/, ‘/’))。
此方案简洁、可维护,无需依赖框架,开箱即用于 Metrical 及任何基于 Bootstrap 的侧边栏导航系统。