You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写eventListener实现鼠标悬浮修改带指定class的div颜色

现有代码问题分析

  • 选择器书写错误:document.querySelectorAll('grid-item') 是标签选择器,要选中类名为grid-item的元素需要加.前缀,正确写法是document.querySelectorAll('.grid-item')
  • querySelectorAll返回的是节点集合,不能直接对整个集合设置style属性,需要针对单个元素操作
  • changeColor函数没有绑定当前触发悬浮事件的元素,执行时会报错或者修改所有元素不符合预期
  • 循环变量c没有声明就使用,会污染全局作用域

修正后的JS代码

const container = document.getElementById('container');

function makeRows(rows, cols) {
  container.style.setProperty('--grid-rows', rows);
  container.style.setProperty('--grid-cols', cols);
  // 声明循环变量c
  for (let c = 0; c < (rows * cols); c++) {
    let cell = document.createElement('div');
    cell.innerText = (c + 1);
    container.appendChild(cell).className = 'grid-item';
  }
}

makeRows(16, 16);

// 直接绑定事件处理当前悬浮元素
const gridItems = document.getElementsByClassName('grid-item');
for (let i = 0; i < gridItems.length; i++) {
  gridItems[i].addEventListener('mouseover', function() {
    // this指向当前触发事件的grid-item元素,改背景色替换为style.backgroundColor即可
    this.style.color = 'blue';
  });
  // 鼠标移出恢复原色可以添加以下监听,不需要可以删掉
  gridItems[i].addEventListener('mouseout', function() {
    this.style.color = 'initial';
  });
}

其他实现方案

方案1:CSS伪类实现(最推荐,性能最优)

不需要编写JS代码,直接添加CSS样式即可,浏览器原生支持响应悬浮事件,性能远高于JS实现,也不需要手动绑定事件:

.grid-item:hover {
  color: blue;
  /* 要修改背景色替换为 background-color: 颜色值 即可 */
}

方案2:事件委托实现

如果网格元素会动态增减,使用事件委托只需要给父容器绑定一次事件即可,不需要每次新增元素都重新绑定监听:

const container = document.getElementById('container');
// 监听悬浮进入
container.addEventListener('mouseover', function(e) {
  if (e.target.classList.contains('grid-item')) {
    e.target.style.color = 'blue';
  }
});
// 监听悬浮移出
container.addEventListener('mouseout', function(e) {
  if (e.target.classList.contains('grid-item')) {
    e.target.style.color = 'initial';
  }
});

内容的提问来源于stack exchange,提问作者George Barda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 04:57:00