我正在编写一个提供 RGB 颜色的简单游戏,即。 rgb(247, 237, 237),并要求玩家选择一个具有最接近匹配颜色的方 block 。默认模式是有 6 个彩色方 block 的困难模式,简单模式有 3 个方 block 。所以最初每个方 block <div class="square"></div>
使用 .square CSS 类来设置样式。 (请参阅下面的 .html 文件)
所以在我开始游戏后,我点击了简单模式,我的代码删除了底部 3 个方 block 的 .square css 类。但是,当我从简单模式切换到困难模式时,我需要点击“困难”模式按钮“两次”才能工作。我发现它的 b/c .square css 类仅在单击“第二次”时添加。 我的问题:第一次单击困难模式时如何添加 .square 类? (请参阅下面标记为的 .js 文件://===> QUESTION)
.html 文件:
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
.js文件:
function setupModeButtons() {
for (var i = 0; i < modeButtons.length; i++) {
modeButtons[i].addEventListener("click", function() {
// If "Easy" Button is clicked,
if (this.textContent === "Easy") {
numSquares = 3
modeButtons[0].classList.remove("selected");
modeButtons[1].classList.remove("selected");
this.classList.add("selected");
// Remove the original bottom 3 squares
for (var i = 3; i < colors.length; i++) {
squares[i].classList.remove("square");
}
// Reset the top 3 squares
colors = [];
generateRandomColors(3);
pickedColor = pickColor();
setupSquares();
}
// If "Hard" Button is clicked,
if (this.textContent === "Hard") {
numSquares = 6;
modeButtons[0].classList.remove("selected");
modeButtons[1].classList.remove("selected");
this.classList.add("selected");
// Add bottom 3 squares
for (var i = 3; i < colors.length; i++) {
squares[i].classList.add("square"); // ===> QUESTION
}
generateRandomColors(6);
pickedColor = pickColor();
setupSquares();
}
}); // End of AddEventListener()
}
}
最佳答案
我假设 generateRandomColors
是填充 colors
数组的内容:你的问题是
generateRandomColors(6);
在您的之后运行
// Add bottom 3 squares
for (var i = 3; i < colors.length; i++) {
所以当 Easy 上只有 3 种颜色时,第一次单击按钮时 for 循环根本不会运行。
只需将其更改为:
generateRandomColors(6);
// Add bottom 3 squares
for (var i = 3; i < colors.length; i++) {
squares[i].classList.add("square"); // ===> QUESTION
}
关于javascript - 在单击第二个按钮之前不会添加 .css 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49459140/