因此,我有一个包含少量颜色的简单数组,以及一个将这些颜色添加到主体的backgroundColor属性中的函数。我正在使用setInterval来遍历颜色,但是当它遍历数组时,它会停止。我希望它继续下去,要么从头开始,要么以相反的顺序进行。我该怎么做呢?
let colors = ['crimson','dodgerblue','gold', 'deeppink'];
const body = document.body;
let index = 0;
function change() {
body.style.backgroundColor = colors[index++];
}
var timer = setInterval(change, 4000);发布于 2021-01-31 23:35:55
let colors = ['green','dodgerblue','gold', 'deeppink'];
const body = document.body;
let index = 0;
function change() {
console.log('going')
body.style.backgroundColor = colors[index++];
if(index == colors.length) {
index = 0;
}
}
var timer = setInterval(change, 1000);
我只是添加了一些逻辑,如果index到达数组的末尾,则将其重置为零
https://stackoverflow.com/questions/65980894
复制相似问题