通过 javascript 在页面加载时解析当前 url,遍历侧边栏所有导航链接,匹配 `href` 并为对应项动态添加 `active` 类,实现菜单项自动激活。
在基于 Metrical Dashboard(一个轻量、Bootstrap 5 驱动的管理仪表盘

✅ 推荐写法(兼容性强、语义清晰):
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');
}
});
});? 关键说明与注意事项:
? 进阶提示:
如需支持「模糊匹配」(例如 /user/123 应激活 /user 菜单项),可将 === 替换为 currentPath.startsWith(linkPath),并确保 linkPath 以 / 结尾(如 linkPath = linkPath.replace(/\/?$/, '/'))。
此方案简洁、可维护,无需依赖框架,开箱即用于 Metrical 及任何基于 Bootstrap 的侧边栏导航系统。