js实现 active
实现 active 状态的 JavaScript 方法
在 JavaScript 中,实现 active 状态通常涉及动态添加或移除 CSS 类,以改变元素的样式。以下是几种常见的方法:
使用 classList API
通过 classList.add() 和 classList.remove() 方法可以方便地切换 active 类:
const element = document.querySelector('.target');
element.addEventListener('click', function() {
this.classList.toggle('active');
});
直接修改 className 属性
对于较老浏览器兼容性,可以直接操作 className:
const btn = document.getElementById('button');
btn.onclick = function() {
if (this.className.indexOf('active') === -1) {
this.className += ' active';
} else {
this.className = this.className.replace('active', '');
}
};
事件委托实现多个元素
当需要处理多个元素时,事件委托更高效:
document.addEventListener('click', function(e) {
if (e.target.matches('.item')) {
document.querySelectorAll('.item').forEach(el => {
el.classList.remove('active');
});
e.target.classList.add('active');
}
});
配合 CSS 过渡效果
添加平滑的视觉反馈:
.button {
transition: background-color 0.3s ease;
}
.button.active {
background-color: #4CAF50;
}
实际应用示例
导航菜单高亮
const navItems = document.querySelectorAll('.nav-item');
navItems.forEach(item => {
item.addEventListener('click', () => {
navItems.forEach(i => i.classList.remove('active'));
item.classList.add('active');
});
});
表单输入框聚焦样式

const inputs = document.querySelectorAll('input');
inputs.forEach(input => {
input.addEventListener('focus', () => {
input.parentElement.classList.add('active');
});
input.addEventListener('blur', () => {
input.parentElement.classList.remove('active');
});
});
这些方法可以根据具体需求进行组合和调整,实现各种交互场景下的 active 状态效果。






