3 回答
![?](http://img1.sycdn.imooc.com/5458506b0001de5502200220-100-100.jpg)
TA贡献1898条经验 获得超8个赞
背景更改有效,因为 getElementById 只返回一个可以设置样式属性的元素。
getElementsByClassName() 但是返回一个项目集合。您将不得不迭代它并更改每个元素的样式元素。尝试这个:
function changeText() {
var col = document.getElementsByClassName("textcolor");
if (colorIndex >= colors.length) {
colorIndex = 0;
}
for(var i = 0; i < col.length; i++){
col[i].style.color = colors[colorIndex];
}
colorIndex++;
}
此外,您不需要 .body 来设置样式。
![?](http://img1.sycdn.imooc.com/533e4d00000171e602000200-100-100.jpg)
TA贡献1809条经验 获得超8个赞
你为什么不给它唯一的 ID 并检查它
let colors = ["green", "red", "blue"];
let colorIndex = 0;
function changeBackground() {
let col = document.getElementById("bodycolor");
if (colorIndex >= colors.length) {
colorIndex = 0;
}
col.style.backgroundColor = colors[colorIndex];
colorIndex++;
let h1Color = document.getElementById("h1Color")
let pColor = document.getElementById("pColor");
if (colorIndex >= colors.length) {
colorIndex = 0;
}
h1Color.style.color = colors[colorIndex];
pColor.style.color = colors[colorIndex];
colorIndex++;
}
<body id='bodycolor'>
<h1 id="h1Color">Title Color Change</h1><br>
<p id="pColor">Text Color Change </p><br>
<button type="button" onclick="changeBackground()">Click me</button>
</body>
![?](http://img1.sycdn.imooc.com/5333a1d100010c2602000200-100-100.jpg)
TA贡献1951条经验 获得超3个赞
getElementsByClassName 返回包含提到的类名的所有元素的数组
尝试
col[0].style.color = colors[colorIndex];
这是您的工作示例
访问https://codepen.io/vikas_saini/pen/jOOErNZ
添加回答
举报