Eventoverener for'mouseover'and'mouseleave'

问题描述 投票:0回答:2

我试图使每个单元格在鼠标悬停在它们上方时改变颜色,并在鼠标离开时将其恢复为默认颜色。我只用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 = '';
});``
javascript events mouseevent mouseover mouseleave
2个回答
0
投票

请原谅我,如果这似乎是一个愚蠢的建议,但为什么不为此使用css:hover属性呢?

.grid-item:hover {
  background-color: black;
}

https://www.w3schools.com/cssref/sel_hover.asp


0
投票

如果只能使用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);
© www.soinside.com 2019 - 2024. All rights reserved.