Style.backgroundColor或style.background没有执行它的功能

时间:2019-01-19 13:10:22

标签: javascript html css

问题

运行此代码时,我的div的背景色未更改:

代码

var colors = [
    "rgb (255, 0, 0)",
    "rgb (255, 255, 0)",
    "rgb (0, 255, 0)",
    "rgb (0, 255, 255)",
    "rgb (0, 0, 255)",
    "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++){
    squares[i].style.backgroundColor = colors[i];
}
body {
    background-color: #232323;
}

.square {
    width: 30%;
    background: purple;
    padding-bottom: 30%;
    float: left;
    margin: 1.6%;
}

#container {
    max-width: 600px;
    margin: 0 auto;
}

h1 {
    color: white;
}
<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>

预期

我应该得到一个6色的正方形,而不是6个充满紫色的正方形

This is the result I am getting with my code

This is what I should be getting

谢谢大家!

2 个答案:

答案 0 :(得分:0)

您的代码不起作用,因为rgb后面有空格

您的代码:form_win = ['2/5','1/4','3/2','4/1','5/8','1/3','7/10','8/6'] form_chr = ['a','b','c','d','e','f','g','h'] b=[] for cnt, a in enumerate(form_win): if re.match(r'^1\/', a) != None: b.extend(form_chr[cnt]) print ('uglyst:',b)

应该是这样

rgb (255,0,0)

希望这会有所帮助。

答案 1 :(得分:0)

只需在rgb颜色之后删除空间,然后我就为getElementsByClassName添加square

var colors = [
    "rgb(255, 0, 0)",
    "rgb(255, 255, 0)",
    "rgb(0, 255, 0)",
    "rgb(0, 255, 255)",
    "rgb(0, 0, 255)",
    "rgb(255, 0, 255)"
]

var squares = document.getElementsByClassName("square");
var pickedColor = colors[3];
var colorDisplay = document.getElementById ("colorDisplay");

colorDisplay.textContent = pickedColor;

for(var i = 0; i < squares.length; i++){    
    squares[i].style.backgroundColor = colors[i];
}
body {
    background-color: #232323;
}

.square {
    width: 30%;
    background: purple;
    padding-bottom: 30%;
    float: left;
    margin: 1.6%;
}

#container {
    max-width: 600px;
    margin: 0 auto;
}

h1 {
    color: white;
}
<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>