在JavaScript中实现菜单高亮当前栏目的功能,通常涉及到以下几个基础概念:
<ul id="menu">
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
#menu li {
display: inline-block;
margin-right: 10px;
}
#menu li.active a {
color: red; /* 高亮颜色 */
font-weight: bold;
}
document.addEventListener('DOMContentLoaded', function() {
const menuItems = document.querySelectorAll('#menu li a');
menuItems.forEach(item => {
item.addEventListener('click', function(event) {
event.preventDefault(); // 阻止默认行为
// 移除所有菜单项的高亮状态
menuItems.forEach(link => link.parentElement.classList.remove('active'));
// 给当前点击的菜单项添加高亮状态
this.parentElement.classList.add('active');
});
});
});
document.addEventListener('DOMContentLoaded', function() {
const menuItems = document.querySelectorAll('#menu li a');
// 初始化高亮状态
const hash = window.location.hash;
if (hash) {
const initialItem = document.querySelector(`a[href="${hash}"]`);
if (initialItem) {
initialItem.parentElement.classList.add('active');
}
}
menuItems.forEach(item => {
item.addEventListener('click', function(event) {
event.preventDefault();
menuItems.forEach(link => link.parentElement.classList.remove('active'));
this.parentElement.classList.add('active');
// 更新URL hash
window.location.hash = this.getAttribute('href');
});
});
});
通过这种方式,即使页面刷新,当前栏目的高亮状态也能得以保持。
领取专属 10元无门槛券
手把手带您无忧上云