没关系HTML和CSS,我已经编写了我的JS,并评论了我可能做的一切,使其易于理解。基本上,它是一个色彩猜谜游戏,由于某种原因,我无法使逻辑正常工作,任何人都可以找出错误吗?
//Array of RGB colors for debuuging purpose
var colors = [
"RGB(255, 0, 0)",
"RGB(255, 255, 0)",
"RGB(255, 0, 255)",
"RGB(0, 255, 255)",
"RGB(0, 255, 0)",
"RGB(0, 0, 255)" ]
//Get all square class divs and put inside "squares"
var squares = document.querySelectorAll(".square");
//pick a set color as the right color for debugging purpose
var pickedColor = colors[3];
//Mach HTML <span> tag
//******************************************************
var colorDisplay = document.getElementById("colorDisplay");
colorDisplay.textContent = pickedColor;
//******************************************************
//loop through all the squares and assign
// a set color from "colors" array
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){
this.style.background = white;
} else {
this.style.background = "#232323";
//Bug: For some reason, if statment is never
//true. I can't find the problem please help.
}
})
}
答案 0 :(得分:1)
当您执行作业squares[i].style.background = colors[i];
时,您正在为样式分配"RGB(255, 0, 0)"
等字符串,浏览器会将字符串规范化为"rgb(255, 0, 0)"
等字符串。如果您只使用rgb
代替RGB
,那么它就会起作用。
另一个问题是你没有定义white
。
以下是修复了错误的代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
.square {
width: 150px;
height: 150px;
float: left;
}
</style>
</head>
<body>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<span id="colorDisplay"></span>
<script>
var white = "RGB(255, 255, 255)"; // Adding white var.
var colors = [
"RGB(255, 0, 0)",
"RGB(255, 255, 0)",
"RGB(255, 0, 255)",
"RGB(0, 255, 255)",
"RGB(0, 255, 0)",
"RGB(0, 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++) {
squares[i].style.background = colors[i];
squares[i].addEventListener("click", function(){
var clickedColor = this.style.background;
// Using lower case
if(clickedColor === pickedColor.toLowerCase()){
this.style.background = white;
} else {
this.style.background = "#232323";
}
});
}
</script>
</body>
</html>
答案 1 :(得分:0)
this.style.background
包含颜色,图像,重复等不同信息。
pickedColor
是一个只有&#34; RGB(x,y,z)&#34;的字符串。
正确的问题是:他们为什么要一样?
Here更多关于this.style.background
的信息修改强>
在检查实践时,您的RGB
已转换为rgb
答案 2 :(得分:0)
我想通了!!!!
出于某种原因,我本来应该写rgb而不是RGB,这导致了另一个我很快想到的错误,我把白色写成变量,而不是&#34; white&#34;作为一个字符串。