我想使用JavaScript使网页每秒更改一次背景颜色。
我正在使用setTimeout
,但我无法弄清楚如何在函数中更改变量。这是我的代码:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function changecolors() {
x = 1; // <-- I know this is wrong, I just don't know where to place it
var t = setTimeout("change()", 1000);
}
function change() {
while(x < 3) {
if(x = 1) {
color = "red";
x++;
} else if (x = 2) {
color = "green";
x = 1;
}
document.body.style.background = color;
}
}
</head>
<body onload="changecolors()">
</body>
</html>
x
将永远小于3
)。(c) 你正在赋值而不是比较。(d) 你只在一秒后调用函数一次,而不是每秒调用。 - Felix Kling