我是初学者,我想将彩色游戏作为一个项目。 html包含六个网格,但javascript显示错误?
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");
for (var i = 0; i < squares.length; i++){
squares[i].style.background-color = colors[i];
}
答案 0 :(得分:1)
它抛出一个错误,因为style.background-color中有一个破折号并且无效。您可以使用背景
for (var i = 0; i < squares.length; i++){
squares[i].style.background = colors[i];
}
或backgroundColor如下,
squares[i].style.backgroundColor = colors[i];
答案 1 :(得分:0)
您的代码中存在两个问题:
rgb (255, 0, 0)
中不应有空格。在rgb(255, 0, 0)
rgb
第二个问题是background-color
应为backgroundColor
。
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");
for (var i = 0; i < squares.length; i++){
squares[i].style.backgroundColor = colors[i];
}
<div class='square'>Color 1</div>
<div class='square'>Color 2</div>
<div class='square'>Color 3</div>
<div class='square'>Color 4</div>
<div class='square'>Color 5</div>
<div class='square'>Color 6</div>