1 回答

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
我認(rèn)為您可以通過類名獲取所有元素(然后循環(huán)遍歷它們以單獨(dú)添加偵聽器。
請(qǐng)參閱下面的演示
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>
添加回答
舉報(bào)