首页 > 解决方案 > 'mouseover' 和 'mouseleave' 的事件监听器

问题描述

我试图让每个单元格在鼠标悬停在它们上方时改变颜色,并在鼠标离开时将其恢复为默认颜色。我只用 HTML 创建了 .container div,而其他 div 是用 JS 循环创建的,所以我发现执行代码很困难。

我很确定我需要使单元格成为函数之外的变量,但如果是这种情况,我不知道该怎么做。有人可以帮忙吗?

``let container = document.getElementById("container");


function makeRows(rows, cols) {
  container.style.setProperty('--grid-rows', rows);
  container.style.setProperty('--grid-cols', cols);
  for (c = 0; c < (rows * cols); c++) {
    const cell = document.createElement("div");
    cell.innerText = (c + 1);
    container.appendChild(cell).className = "grid-item";
  };
};

makeRows(16, 16);

var gridCells = document.querySelectorAll(".grid-item"); 

gridCells.addEventListener('mouseover', () => {
  gridCells.style.backgroundColor = 'black';
});

gridCells.addEventListener('mouseleave', () => {
  gridCells.style.backgroundColor = '';
});``

标签: javascripteventsmouseeventmouseovermouseleave

解决方案


如果只能使用 javascript,则可以将事件侦听器放入循环中。或者你可以只使用 css.grid-item:hover {background-color: black;}

let container = document.getElementById("container");


function makeRows(rows, cols) {
  container.style.setProperty('--grid-rows', rows);
  container.style.setProperty('--grid-cols', cols);
  for (c = 0; c < (rows * cols); c++) {
    const cell = document.createElement("div");
    cell.innerText = (c + 1);
    container.appendChild(cell).className = "grid-item";
    cell.addEventListener('mouseover', () => {
      cell.style.backgroundColor = 'black';
    });
    cell.addEventListener('mouseleave', () => {
       cell.style.backgroundColor = 'white';
    });
  }
};

makeRows(16, 16);

推荐阅读