鼠标悬停时如何正确修改所有带有特定class的元素的背景色?
问题根源
- 你代码中声明的
heading变量是通过document.querySelector('.heading')获取的,这个API本身的特性就是仅返回首个匹配选择器的DOM元素,后续事件回调中你固定修改这个变量的样式,自然只有第一个heading元素会响应变化 - 额外小问题:你CSS代码中的
.heading2,heading3选择器书写错误,heading3前缺少类选择器标识.,对应的margin-top样式不会生效
修复方案
根据你的需求,分两种实现场景给出对应代码:
场景1:鼠标悬停任意一个heading元素,所有class为heading的元素都统一变色
JS代码调整如下
// 移除无用的首个heading变量声明,直接获取所有匹配元素 const headingAll = document.querySelectorAll('.heading'); headingAll.forEach(item => { item.addEventListener("mouseover",()=>{ // 遍历所有heading元素统一修改背景色 headingAll.forEach(heading => { heading.style.backgroundColor = 'teal'; }); }); // 可选:鼠标移出后所有元素恢复原始背景色 item.addEventListener("mouseout",()=>{ headingAll.forEach(heading => { heading.style.backgroundColor = 'yellow'; }); }); })
场景2:仅当前被鼠标悬停的heading元素单独变色
如果是这个需求,除了改JS之外,也可以直接用CSS伪类实现,性能更高代码更简洁:
方案A:用CSS实现(优先推荐)
在你的CSS代码中新增以下规则即可,无需JS代码:
.heading:hover { background-color: teal; }
方案B:用JS实现
const headingAll = document.querySelectorAll('.heading'); headingAll.forEach(item => { item.addEventListener("mouseover",()=>{ // 直接修改当前触发事件的元素样式即可 item.style.backgroundColor = 'teal'; }); // 可选:鼠标移出后恢复原始背景色 item.addEventListener("mouseout",()=>{ item.style.backgroundColor = 'yellow'; }); })
内容的提问来源于stack exchange,提问作者Ridoy Dey
相关产品推荐
相关产品推荐

