我试图每秒更改正文的背景颜色,但它不起作用。我做错了什么?
var colors = [
"red", "blue", "green", "yellow", "red"
],
rand = Math.ceil(Math.random() * colors.length - 1),
t = setInterval(function() {
document.body.style.backgroundColor = colors[rand];
}, 1000);
最佳答案
您定义了值rand
一次,然后每次都重复使用它。你的意思是:
var colors = [
"red", "blue", "green", "yellow", "red"
];
t = setInterval(function() {
// use floor instead of ceil and then you can skip the -1
var rand = Math.floor(Math.random() * colors.length)
document.body.style.backgroundColor = colors[rand];
}, 1000);
此外,您使用逗号来分隔命令,虽然这并不总是会中断(我可以想到至少一种不会中断的情况),但这通常是一个坏主意,因为它意味着正在发生一些更大的结构。
根据 patrick dw
的评论,您使用逗号是正确的。这让我在这种情况下出现了心理失误,尤其是当 rand
被移入 setInterval
的函数时。我建议您可能需要将其重写为 var Colors, t; colors =
帮助人们了解更多(有一次看起来我不是唯一犯这个错误的人)
关于javascript - 为什么这个 setInterval 代码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7286356/