尝试使用JS.Console制作Color Guessing游戏并没有向我显示任何错误,但它提醒我"错误!"即使我选择了一个正确的数字,当它需要警告"正确!" ...我已经尝试解决这个问题大约三个小时!
如果我删除else{ alert ("Wrong!") }
然后点击颜色,则根本没有回调。如果我输入控制台square[i].style.background
,它会返回我
undefined
这是我的代码:
var colors = [
"rgb(255,0,0)",
"rgb(255,255,0)",
"rgb(0,255,0)",
"rgb(0,255,255)",
"rgb(0,0,225)",
"rgb(255,0,255)"
]
var squares = document.querySelectorAll(".square");
var pickedColor = colors [3];
var colorDisplay = document.getElementById("colorDisplay");
colorDisplay.textContent = pickedColor;
for(var i = 0; i <squares.length;i++){
// add initial colors to squares
squares[i].style.background = colors[i];
// add click listeners to squares
squares[i].addEventListener ("click",function() {
// grab color of clicked square
var clickedColor = this.style.background;
// compare color to pickedColor
if(clickedColor === pickedColor){
alert("Correct!");
} else {
alert("Wrong!")
}
});
}
这是我的HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Color Game</title>
<link rel="stylesheet" type="text/css" href="colorGame.css">
</head>
<body>
<h1>The Great <span id="colorDisplay">RGB</span> Color Game</h1>
<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>
<script src="colorGame.js"></script>
</body>
</html>
答案 0 :(得分:2)
您使用了img.onload
。您应该使用的是style.background
style.backgroundColor
属性包含:
答案 1 :(得分:0)
this.style.background
提供的格式与数组中的格式略有不同,因为它在每个逗号后都有空格(在Chrome中)。这很容易解决。
我想通过将元素上的颜色作为类(或其他某些属性)存储来避免此问题(以及浏览器特定问题),然后只检查该属性是否相同。这样,您的输入就不会被浏览器修改。
var colors = [
"rgb(255,0,0)",
"rgb(255,255,0)",
"rgb(0,255,0)",
"rgb(0,255,255)",
"rgb(0,0,225)",
"rgb(255,0,255)"
]
var squares = document.querySelectorAll(".square");
var pickedColor = colors [3];
var colorDisplay = document.getElementById("colorDisplay");
colorDisplay.textContent = pickedColor;
for(var i = 0; i <squares.length;i++){
// add initial colors to squares
squares[i].style.background = colors[i];
// add as class
squares[i].classList.add(colors[i]);
// add click listeners to squares
squares[i].addEventListener ("click",function() {
// compare color to pickedColor
if(this.classList.contains(pickedColor)){
alert("Correct!");
} else {
alert("Wrong!")
}
});
}
&#13;
.square{
width : 100px;
height : 100px;
}
&#13;
<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 id="colorDisplay" />
&#13;