js实现高亮切换
实现高亮切换的 JavaScript 方法
使用 classList 切换类名
通过 classList.toggle() 动态添加或移除高亮样式类,适用于现代浏览器。
const element = document.getElementById('target');
element.addEventListener('click', () => {
element.classList.toggle('highlight');
});
CSS 部分需定义高亮样式:
.highlight {
background-color: yellow;
color: black;
}
动态修改 style 属性
直接操作元素的 style 属性实现即时样式变更:
const element = document.querySelector('.item');
let isHighlighted = false;
element.addEventListener('click', () => {
isHighlighted = !isHighlighted;
element.style.backgroundColor = isHighlighted ? '#ffeb3b' : '';
element.style.color = isHighlighted ? '#000' : '';
});
多元素高亮切换
为多个元素实现单选高亮效果时,需先清除其他元素的高亮状态:
const items = document.querySelectorAll('.list-item');
items.forEach(item => {
item.addEventListener('click', () => {
items.forEach(i => i.classList.remove('active'));
item.classList.add('active');
});
});
使用 data-* 属性存储状态
通过自定义属性记录高亮状态,适合复杂交互场景:
document.querySelectorAll('[data-highlight]').forEach(el => {
el.addEventListener('click', function() {
const currentState = this.getAttribute('data-highlight');
this.setAttribute('data-highlight', currentState === 'on' ? 'off' : 'on');
this.style.backgroundColor = currentState === 'on' ? '' : 'gold';
});
});
动画高亮效果
结合 CSS transition 实现平滑的高亮过渡:
.highlight-transition {
transition: background-color 0.3s ease;
}
document.getElementById('animated-btn').addEventListener('click', function() {
this.classList.toggle('highlight');
});
键盘导航高亮
通过键盘事件实现高亮切换:
let currentIndex = 0;
const menuItems = document.querySelectorAll('.menu-item');
document.addEventListener('keydown', (e) => {
if (e.key === 'ArrowDown') {
menuItems[currentIndex].classList.remove('highlight');
currentIndex = (currentIndex + 1) % menuItems.length;
menuItems[currentIndex].classList.add('highlight');
}
if (e.key === 'ArrowUp') {
menuItems[currentIndex].classList.remove('highlight');
currentIndex = (currentIndex - 1 + menuItems.length) % menuItems.length;
menuItems[currentIndex].classList.add('highlight');
}
});
性能优化建议
对于大量元素的高亮操作,建议使用事件委托:

document.getElementById('container').addEventListener('click', (e) => {
if (e.target.matches('.highlightable')) {
e.target.classList.toggle('active');
}
});






