js实现hover
使用CSS实现hover效果
在CSS中直接使用:hover伪类是最简单的方法,无需JavaScript。例如改变链接颜色:
a:hover {
color: red;
text-decoration: underline;
}
使用JavaScript监听mouseover/mouseout事件
通过添加事件监听器实现类似效果:
const element = document.getElementById('hoverElement');
element.addEventListener('mouseover', function() {
this.style.backgroundColor = 'yellow';
});
element.addEventListener('mouseout', function() {
this.style.backgroundColor = '';
});
使用classList切换CSS类
更推荐的做法是通过切换CSS类来实现样式变化:

const box = document.querySelector('.box');
box.addEventListener('mouseenter', () => {
box.classList.add('hover-active');
});
box.addEventListener('mouseleave', () => {
box.classList.remove('hover-active');
});
对应CSS:
.box.hover-active {
transform: scale(1.1);
box-shadow: 0 0 10px rgba(0,0,0,0.2);
}
实现延迟显示效果
结合setTimeout实现悬停延迟显示:

let hoverTimer;
element.addEventListener('mouseover', () => {
hoverTimer = setTimeout(() => {
element.style.opacity = '0.8';
}, 300);
});
element.addEventListener('mouseout', () => {
clearTimeout(hoverTimer);
element.style.opacity = '1';
});
事件委托处理动态元素
对于动态生成的元素,使用事件委托:
document.body.addEventListener('mouseover', function(e) {
if(e.target.classList.contains('dynamic-item')) {
e.target.style.border = '2px solid blue';
}
});
结合CSS变量实现主题切换
通过JavaScript修改CSS变量实现主题切换:
document.documentElement.addEventListener('mouseover', (e) => {
if(e.target.matches('.theme-item')) {
document.documentElement.style.setProperty('--hover-color', e.target.dataset.color);
}
});






