javascript - '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 = '';
});``
解决方案
如果只能使用 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);
推荐阅读
- javascript - 无法使用 localstorage.clear() 清除本地存储;
- python - 在数据透视表中的 Aggfunc 中应用百分位数的 python 代码是什么?
- pymongo - 是否有一种方法可以将文件存储在特定目录下的 mongo 中
- aws-api-gateway - amazon api 网关返回 403
- javascript - 用高阶函数替换我的 for 循环以在我的搜索组件中获取关键字?
- javascript - 如何以正确的方式使用等待eslint(序列查询)
- php - idn_to_ascii():INTL_IDNA_VARIANT_2003 已弃用
- reactjs - React Module Not Found,我从来没有遇到过这个问题
- delphi - Delphi Frame继承属性不存在
- kotlin-multiplatform - 在多平台模块上使用 kotest FreeSpec