我正在尝试在屏幕上生成5个正方形,当我将鼠标悬停在其中一个正方形上时,正方形的背景颜色变为黑色。将鼠标悬停在元素上后,我将“ hit”类应用于该元素。 hit类仅应用于已生成的最后一个正方形。但不适用于其他任何人。我看过其他一些我知道与我类似的stackoverflow问题,但由于我未在javaScript代码中修改innerHTML而似乎找不到答案。
我无法在该项目中使用JQuery。
HTML代码:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Etch A Sketch</title>
<link rel="stylesheet" href="styles/style.css">
</head>
<body>
<div id="grid">
</div>
<script type="text/javascript" src="scripts/app.js"></script>
</body>
</html>
JavaScript代码:
let grid = document.querySelector("#grid"); //The grid is the border that surrounds all of the squares
for (i=0; i < 5; i++) {
square = document.createElement("div");
square.classList.add("square"); //The "square" class creates the square out of the div
grid.appendChild(square);
}
square.addEventListener("mouseover", function () {
square.classList.add("hit"); //The "hit" class just changes the background color of the square to black
})
CSS代码:
.square {
display: inline-grid;
width: 31px;
height: 31px;
border: 3px solid black;
}
.hit {
background-color: black;
}
#grid {
position: absolute;
top: 50%;
left: 50%;
margin-top: -250px;
margin-left: -250px;
width: 500px;
height: 500px;
border: 3px solid black;
}
该类仅被应用于最后一个元素,因为您是在循环之外添加事件侦听器,因此它仅将其应用于square
的最后一个实例。另外请注意,在使用变量之前,应先声明变量。在您的示例中,您无需初始化就使用square
。看到这里:
let grid = document.querySelector("#grid"); //The grid is the border that surrounds all of the squares
for (i = 0; i < 5; i++) {
let square = document.createElement("div");
square.classList.add("square"); //The "square" class creates the square out of the div
grid.appendChild(square);
square.addEventListener("mouseover", function() {
square.classList.add("hit"); //The "hit" class just changes the background color of the square to black
})
}
.square {
display: inline-grid;
width: 31px;
height: 31px;
border: 3px solid black;
}
.hit {
background-color: black;
}
#grid {
position: absolute;
top: 50%;
left: 50%;
margin-top: -250px;
margin-left: -250px;
width: 500px;
height: 500px;
border: 3px solid black;
}
<div id="grid"></div>