3 回答

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 來設置樣式。

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>

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