不管我怎么尝试,我都不能让它起作用。如果我用.getElementById
,它就能用.但是我需要针对多个divs
,所以我需要使用.getElementsByClassName
。
到目前为止,我的情况如下:
function changeBgColor(color){
document.getElementById("background1").style.background = color;
}
function changeBackground(color){
document.getElementsByClassName("pls-work").style.background = color;
}
#background1{
background: #c0c0c0;
padding: 50px;
color: #fafafa;
}
.background2{
background: #ff7f50;
padding: 20px;
}
.background3{
background: #555;
padding: 20px;
}
<h4>First example</h4>
<div id="background1"><p>My background color will change.</p></div>
<button onclick="changeBgColor('#222');">This function will work, no problem</button>
<br><br>
<h4>Second example</h4>
<div class="background3 pls-work"><p>My background color and my sibling's won't.</p></div>
<div class="background2 pls-work"><p>I am the sibling</p></div>
<button onclick="changeBackground('#222');">This will not work</button>
我到处搜索,但我找不到他们使用class
而不是id
的地方。
如果你能给我指点我做错了什么,我会很感激。
发布于 2021-10-21 05:11:11
请试试这个,
首先,在变量中获取该元素,并对其进行循环。
function changeBackground(color){
var elements = document.getElementsByClassName("pls-work")
for (var i = 0; i < elements.length; i++) {
elements[i].style.background=color;
}
}
发布于 2021-10-21 05:06:30
getElementsByClassName返回需要迭代的元素的“类似数组的对象”,而不是返回单个元素的getElementById
。
看看这个:
const changeBgColor = () => {
const elements = document.getElementsByClassName('color-me');
const color = document.querySelector('input').value;
for (let i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = color;
}
};
<p class='color-me'>Color me!</p>
<p>Can't change me..</p>
<p class='color-me'>Me too!</p>
<input type=color />
<button onclick=changeBgColor()>Click Me</button>
发布于 2021-10-21 05:08:41
对document.getElementsByClassName("pls-work")
的调用返回元素的HTMLCollection
,而不是单个元素。您需要对集合进行迭代,并对每个元素设置样式属性。
https://stackoverflow.com/questions/69656107
复制相似问题