使用类更改单击背景色

时间:2019-10-26 03:59:59

标签: javascript colors

这是我的代码:

function black() {
document.querySelectorAll(".object").style.backgroundColor = "black";
}

function red() {
document.querySelectorAll(".object").style.backgroundColor = "red";
}

function blue() {
document.querySelectorAll(".object").style.backgroundColor = "blue";
}
.object {
width: 200px;
height: 200px;
background-color: black;
margin: 20px;
}
<button id="button_black" class="color_change" onclick="black()" value="black">Black</button>
<button id="button_red" class="color_change" onclick="red()" value="red">Red</button>
<button id="button_blue" class="color_change" onclick="blue()" value="blue">Blue</button>


<div class="object"></div>
<div class="object"></div>

不幸的是,它不起作用。如果我将»document.querySelectorAll«更改为»document.querySelector«并使用ID,则它适用于一个对象。但是我需要它作为课程。如何解决?

Thaaanks。

1 个答案:

答案 0 :(得分:1)

您的问题是document.querySelectorAll返回一个NodeList,您需要遍历其中的值,并更改每个NodeBack的背景:

function black() {
document.querySelectorAll(".object").forEach(v => v.style.backgroundColor = "black");
}

function red() {
document.querySelectorAll(".object").forEach(v => v.style.backgroundColor = "red");
}

function blue() {
document.querySelectorAll(".object").forEach(v => v.style.backgroundColor = "blue");
}
.object {
width: 200px;
height: 200px;
background-color: black;
margin: 20px;
}
<button id="button_black" class="color_change" onclick="black()" value="black">Black</button>
<button id="button_red" class="color_change" onclick="red()" value="red">Red</button>
<button id="button_blue" class="color_change" onclick="blue()" value="blue">Blue</button>


<div class="object"></div>
<div class="object"></div>