这个代码实际上应该在每次按下按钮改变它的类时改变颜色。 但不幸的是,直到数组的最后一个值才会落空,我不太明白为什么会这样做。按钮最终变成紫色。希望你有个主意。
HTML和CSS应该没问题。
谢谢!
代码:
function changeClass() {
var classVariations = ["red", "blue", "yellow,", "pink", "purple"];
for (var i = 0; i < classVariations.length; i++) {
document.getElementById("differentColors").classList.add(classVariations[i]);
}
}
function changeColor() {
document.getElementById("differentColors").addEventListener("click", changeClass);
document.getElementById("differentColors").classList.remove(classVariations[i]);
}
window.addEventListener("load", changeColor);
&#13;
.red {
background-color: red;
}
.blue {
background-color: blue;
}
.yellow {
background-color: yellow;
}
.pink {
background-color: pink;
}
.purple {
background-color: purple;
}
&#13;
<button id="differentColors">Change my color.</button>
&#13;
答案 0 :(得分:1)
这里的问题是因为它正在运行每种颜色并将颜色设置为最后一个数组元素。所以它基本上立即改变了所有数组元素的颜色,比你注意到的要快。
将JavaScript更改为以下内容应该有效。
var currentColorIndex = 0;
var classVariations = ["red", "blue", "yellow", "pink", "purple"];
function changeClass() {
document.getElementById("differentColors").classList.remove(classVariations[currentColorIndex]); // remove current color
if (currentColorIndex != classVariations.length - 1) {
currentColorIndex++; // increase current color index
} else {
currentColorIndex = 0; // reset current color index to 0 since it's the end of the array
}
document.getElementById("differentColors").classList.add(classVariations[currentColorIndex]); // set new color
}
function changeColor() {
document.getElementById("differentColors").addEventListener("click", changeClass);
document.getElementById("differentColors").classList.add(classVariations[currentColorIndex]); // set first color to first color in array
}
window.addEventListener("load", changeColor);
基本上存储当前颜色并在每次单击时将其递增1。
答案 1 :(得分:1)
变量范围存在一些问题。而且你瞬间完成所有颜色的循环。在我的头顶,我就是这样做的:
var classVariations = ["red", "blue", "yellow", "pink", "purple"];
var i = 0;
var $myBtn = document.getElementById("differentColors")
function changeClass() {
let iNew = i < classVariations.length-1 ? i + 1 : 0;
$myBtn.classList.remove(classVariations[i]);
$myBtn.classList.add(classVariations[iNew]);
i = iNew;
}
function changeColor() {
$myBtn.addEventListener("click", changeClass);
}
window.addEventListener("load", changeColor);
我也缓存了DOM选择器,因为这是一个很好的做法。还修正了一个拼写错误 - 黄色字符串中的虚假逗号。
答案 2 :(得分:1)
试试这个
var classVariations = ["red", "blue", "yellow", "pink", "purple"];
var count = 0;
function changeClass() {
document.getElementById("differentColors").className = classVariations[count];
count = count < classVariations.length ? count + 1 : 0;
}
function changeColor() {
document.getElementById("differentColors").addEventListener("click", changeClass);
}
window.addEventListener("load", changeColor);