1 回答
TA贡献1848条经验 获得超6个赞
我认为您可以通过类名获取所有元素(然后循环遍历它们以单独添加侦听器。
请参阅下面的演示
const container = document.getElementById("container");
function makeRows(rows, columns) {
container.style.setProperty('--grid-rows', rows);
container.style.setProperty('--grid-cols', columns);
for (c = 0; c < (rows * columns); c++) {
let cell = document.createElement("div");
//cell.innerText = (c + 1);
container.appendChild(cell).className = "grid-item";
}
}
//Draw Board
makeRows(16, 16);
//Paint on board
const paint = document.getElementsByClassName("grid-item");
for (var idx = 0; idx < paint.length; idx++) {
paint[idx].addEventListener('mouseover', function() {
this.style.backgroundColor = "black";
});
}
:root {
--grid-cols: 0;
--grid-rows: 0;
}
#container {
display: grid;
padding: 10em;
height: 40vh;
width: 50vh;
margin-left: auto;
margin-right: auto;
grid-template-rows: repeat(var(--grid-rows), 1fr);
grid-template-columns: repeat(var(--grid-cols), 1fr);
}
.grid-item {
padding: 1em;
border: 1px solid #ddd;
text-align: center;
}
<div id="container"></div>
添加回答
举报