3 回答

TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
背景更改有效,因?yàn)?getElementById 只返回一個(gè)可以設(shè)置樣式屬性的元素。
getElementsByClassName() 但是返回一個(gè)項(xiàng)目集合。您將不得不迭代它并更改每個(gè)元素的樣式元素。嘗試這個(gè):
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 來設(shè)置樣式。

TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
你為什么不給它唯一的 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>

TA貢獻(xiàn)1951條經(jīng)驗(yàn) 獲得超3個(gè)贊
getElementsByClassName 返回包含提到的類名的所有元素的數(shù)組
嘗試
col[0].style.color = colors[colorIndex];
這是您的工作示例
訪問https://codepen.io/vikas_saini/pen/jOOErNZ
添加回答
舉報(bào)