我设置了一个包含 5 种颜色的数组,我希望每 5 秒自动旋转/显示这些颜色作为我的背景色。我的 Javascript 代码有效,但我不明白它是如何显示颜色的。
如您所见,我希望首先显示绿色,然后是红色、蓝色、橙色和银色。以该顺序。但是,当我加载页面时,它是完全随机的。例如,当页面加载时它不会显示任何内容,然后是蓝色、红色、蓝色、橙色、红色、银色等……完全随机。为什么会这样,我做错了什么?
function changebackground() {
var colors = ["green", "red", "blue", "orange", "silver"];
setInterval(function() {
var bodyback = Math.floor(Math.random() * colors.length);
var selectedcolor = colors[bodyback];
document.body.style.background = selectedcolor;
}, 5000);
}
window.onload = changebackground();
最佳答案
您正在代码中选择一个随机索引:
var bodyback = Math.floor(Math.random() * colors.length);
相反,您需要通过存储当前索引并递增它来遍历可能的索引:
function changebackground() {
var colors = ["green", "red", "blue", "orange", "silver"];
var curIndex = 0;
setInterval(function() {
var selectedcolor = colors[curIndex];
document.body.style.background = selectedcolor;
curIndex = (curIndex + 1) % colors.length;
}, 5000);
}
window.onload = changebackground();
确保修改 (%) 当前索引,以便在您到达数组末尾时将其重置为开头。
关于javascript - 使用 Javascript 更改背景颜色无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22289464/