【发布时间】:2020-09-04 21:47:04
【问题描述】:
我试图让每个单元格在鼠标悬停在它们上方时改变颜色,并在鼠标离开时将其恢复为默认颜色。我只用 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