因此,我有一个包含少量颜色的简单数组,以及一个将这些颜色添加到主体的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:34:56
您只需要一点额外的逻辑来检查index,如果它超出了数组的末尾,则将其重置为0。
最简单的方法是使用%“模运算符”:
function change() {
index = (index + 1) % colors.length;
body.style.backgroundColor = colors[index];
}发布于 2021-01-31 23:34:56
您必须确保索引到达数组的末尾,如果是,则将其重置。类似于:
function change() {
index = index === colors.length - 1 ? 0 : index++;
body.style.backgroundColor = colors[index];
}发布于 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
复制相似问题