本文介绍了更改类中所有元素的背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个div,当我单击它时,应将.counter类中的所有元素都变为红色,但此刻它什么也不做.我相信您必须先运行一个循环,然后以某种方式使用它来选择类宽度JS中的所有元素?
I have a div, when I clicked on it, should turn all the elements in the .counter class to red, but at the moment it does nothing. I believe you have to run through a loop first and then use this somehow to select all elements in the class width JS?
CSS
.counter {
width: 100px;
height:100px;
background-color:orange;
}
#btn {
background-color:aqua;
width:50px;
height:50px;
position:absolute;
left:200px;
top:10px;
}
HTML
<div class="counter"></div> <br>
<div class="counter"></div> <br>
<div class="counter"></div> <br>
<div class="counter"></div> <br>
<div class="counter"></div>
<div id="btn" onclick="myFunction()"></div>
JS
var myCounters = document.getElementsByClassName("counter")
for (var i = 0; i < myCounters.length; i++){
console.log(myCounters[i])
}
function myFunction() {
document.getElementsByClassName(i).style.backgroundColor = "red"
}
推荐答案
您可以在DOM列表(例如nodeList或HTMLCollection)上使用for/of迭代来完成此操作.因为所有最新版本的现代浏览器(Safari,Firefox,Chrome,Edge)都支持
Hi you can do this using for/of iteration on DOM lists such nodeList or HTMLCollection. since all recent versions of modern browsers (Safari, Firefox, Chrome, Edge) support it
function myFunction() {
let counters = document.getElementsByClassName("counter");
for(let counter of counters){
counter.style.backgroundColor = 'red';
}
}
.counter {
width: 100px;
height:100px;
background-color:orange;
}
#btn {
background-color:aqua;
width:50px;
height:50px;
position:absolute;
left:200px;
top:10px;
}
<div class="counter"></div> <br>
<div class="counter"></div> <br>
<div class="counter"></div> <br>
<div class="counter"></div> <br>
<div class="counter"></div>
<div id="btn" onClick="myFunction()">
</div>
这篇关于更改类中所有元素的背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!