如何让Bootstrap navbar点击时切换active state(激活状态)?
嘿,这个问题真的是新手入门Bootstrap时超常见的坑!我来给你讲几种简单的解决办法,都是新手也能快速上手的~
场景1:多页面网站(点击链接跳转到新页面)
这种情况最直接友好的方式,就是在每个页面的导航栏里,给当前页面对应的导航项手动加上active类。比如:
- 在
index.html(Home页面)里:
<nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <div class="collapse navbar-collapse"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="index.html">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="about.html">About</a> </li> <li class="nav-item"> <a class="nav-link" href="contact.html">Contact</a> </li> </ul> </div> </div> </nav>
- 在
about.html里,把About的nav-link加上active,同时去掉Home的:
<li class="nav-item"> <a class="nav-link" href="index.html">Home</a> </li> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="about.html">About</a> </li>
这种方法完全不需要写JS,对新手来说零门槛,也不容易出错。
场景2:单页面/不想手动改每个页面(用JS自动匹配)
如果你的网站是单页面应用,或者想省掉手动修改每个页面的麻烦,可以用JS自动识别当前页面的URL,给对应的导航项加上active类。
把这段原生JS代码放在每个页面的底部(或者单独的外部JS文件里):
// 页面加载完成后执行 document.addEventListener('DOMContentLoaded', function() { // 获取所有导航链接 const navLinks = document.querySelectorAll('.nav-link'); // 获取当前页面的路径(比如 "/about.html" 或者 "/about") const currentPath = window.location.pathname; // 遍历每个导航链接 navLinks.forEach(link => { // 匹配当前页面路径,同时处理根域名(比如http://xxx.com/对应index.html) if (link.getAttribute('href') === currentPath || (currentPath === '/' && link.getAttribute('href') === 'index.html')) { // 先移除所有导航项的active类 navLinks.forEach(l => l.classList.remove('active')); // 给当前匹配的链接加上active类 link.classList.add('active'); } }); });
小提示:
- 确保导航链接的
href和页面实际路径一致,比如href="about.html"对应/about.html,href="/about"对应/about。 - 如果你的项目已经引入了jQuery,也可以用更简洁的写法:
$(document).ready(function() { $('.nav-link').each(function() { if ($(this).attr('href') === window.location.pathname) { $(this).addClass('active').siblings().removeClass('active'); } }); });
场景3:点击导航不刷新页面(AJAX加载内容)
如果你的网站是单页面,点击导航链接不会刷新页面,而是用AJAX加载内容,那需要在点击事件里手动切换active类:
document.addEventListener('DOMContentLoaded', function() { const navLinks = document.querySelectorAll('.nav-link'); navLinks.forEach(link => { link.addEventListener('click', function(e) { // 阻止默认页面跳转(如果用AJAX加载内容的话) e.preventDefault(); // 移除所有导航项的active类 navLinks.forEach(l => l.classList.remove('active')); // 给当前点击的链接加上active类 this.classList.add('active'); // 这里可以添加AJAX加载内容的代码,比如: // const pageUrl = this.getAttribute('href'); // fetch(pageUrl) // .then(response => response.text()) // .then(html => { // document.getElementById('content-container').innerHTML = html; // }); }); }); });
内容的提问来源于stack exchange,提问作者Jens O. Anders Olsén
相关产品推荐
相关产品推荐

