
Bootstrap 5 默认不自动为当前页面的导航链接添加 .active 类,需手动设置或结合 JavaScript 动态管理;同时需确保引入的是 Bootstrap 5 官方 JS/CSS 资源,避免混用 v4 版本导致行为异常。
bootstrap 5 默认不自动为当前页面的导航链接添加 `.active` 类,需手动设置或结合 javascript 动态管理;同时需确保引入的是 bootstrap 5 官方 js/css 资源,避免混用 v4 版本导致行为异常。
在 Bootstrap 5 中,导航栏(navbar)的 你的 CSS 已正确: ? 提示: 若页面较多,可用轻量 JavaScript 自动匹配当前路径并激活: 下拉项( 并补充 CSS(可选): 遵循以上步骤,即可稳定、语义化地实现 Bootstrap 5 导航高亮,无需 hack 或降级兼容。active 状态不会自动根据当前 URL 更新——它完全依赖开发者显式控制:要么在服务端/静态页中为对应 @#@#@#@#@#@#@#@#@#@0
<!-- ✅ Bootstrap 5 正确 CDN(CSS + JS) -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
.visually-hidden 替代了旧版 .sr-only,语义更规范。3. 动态高亮(单页应用或需要自动化时)
<!-- 在 /index.html 中 -->
4. 下拉菜单中的激活项处理
.dropdown-item)同样需手动添加 active 类:.nav-link.active {
color: red !important; /* 加 !important 确保覆盖 Bootstrap 默认样式 */
}
<script>
document.addEventListener('DOMContentLoaded', function() {
const currentPath = window.location.pathname;
const navLinks = document.querySelectorAll('.navbar-nav .nav-link');
navLinks.forEach(link => {
// 支持子路径匹配(如 /hobby/anime.html → /hobby/)
if (link.getAttribute('href') === currentPath ||
currentPath.startsWith(link.getAttribute('href') + '/') ||
(link.getAttribute('href') === '/' && currentPath === '/index.html')) {
link.classList.add('active');
} else {
link.classList.remove('active');
}
});
});
</script>
总结
active 类必须加在 上(非 ),CSS 才能命中 .nav-link.active;bootstrap.bundle.min.js(含 Popper),禁用 jQuery。<a class="dropdown-item active" href="/hobby/anime.html">Hobby1</a>
.dropdown-item.active {
background-color: #0d6efd;
color: white;
}











