js实现active

使用 JavaScript 实现 active 状态
通过 JavaScript 动态添加或移除 active 类,可以高亮显示当前选中的元素。以下是几种常见实现方式:
通过事件监听器切换 active 状态
// 获取所有需要添加 active 状态的元素
const items = document.querySelectorAll('.item');
// 遍历元素并添加点击事件
items.forEach(item => {
item.addEventListener('click', function() {
// 移除其他元素的 active 类
items.forEach(el => el.classList.remove('active'));
// 为当前点击元素添加 active 类
this.classList.add('active');
});
});
通过事件委托优化性能
// 在父元素上监听点击事件
document.querySelector('.container').addEventListener('click', function(e) {
// 检查点击目标是否是需要添加 active 的元素
if (e.target.classList.contains('item')) {
// 移除所有同类的 active 类
document.querySelectorAll('.item').forEach(el => {
el.classList.remove('active');
});
// 为点击目标添加 active 类
e.target.classList.add('active');
}
});
配合 CSS 实现视觉反馈
.item {
/* 默认样式 */
background-color: #fff;
color: #333;
}
.item.active {
/* 激活状态样式 */
background-color: #007bff;
color: white;
}
在单页应用(SPA)中保持 active 状态
// 根据当前路由设置 active 状态
function setActiveNav() {
const currentPath = window.location.pathname;
const navLinks = document.querySelectorAll('.nav-link');
navLinks.forEach(link => {
if (link.getAttribute('href') === currentPath) {
link.classList.add('active');
} else {
link.classList.remove('active');
}
});
}
// 页面加载时执行
window.addEventListener('DOMContentLoaded', setActiveNav);
// 路由变化时执行
window.addEventListener('popstate', setActiveNav);
使用 dataset 存储状态信息
const buttons = document.querySelectorAll('[data-action]');
buttons.forEach(button => {
button.addEventListener('click', function() {
// 移除所有按钮的 active 状态
document.querySelectorAll('[data-action]').forEach(btn => {
btn.classList.remove('active');
});
// 设置当前按钮为 active
this.classList.add('active');
// 获取 data-action 值执行相应操作
const action = this.dataset.action;
console.log(`执行操作: ${action}`);
});
});







