我有一个fiddle,每隔一秒我就会将背景颜色更改为不同的颜色。
我想知道我需要在下面的Javascript代码中进行哪些更改,因为在10小时后没有颜色变化。我正在使用的JS代码是:
var i = 0;
function change() {
var doc = document.getElementById("background");
var color = ["black", "blue", "brown", "green", "red", "yellow", "white", "pink", "purple", "orange"];
doc.style.backgroundColor = color[i];
i = (i + 1) % color.length;
}
myVar = setInterval(change, 1000);
html,
body {
border: 0;
margin: 0;
height: 100%;
min-height: 100%;
}
.container {
width: 100% !important;
}
#background {
width: 100%;
height: 100%;
}
<div id="background">
</div>
答案 0 :(得分:2)
这样的东西?
var i = 0;
var doc = document.getElementById("background");
var color = ["black", "blue", "brown", "green", "red", "yellow", "white", "pink", "purple", "orange"];
function change() {
if (i < 9) {
doc.style.backgroundColor = color[i];
i = (i + 1);
} else {
doc.style.backgroundColor = color[i];
clearInterval(myVar);
}
}
myVar = setInterval(change, 1000);
&#13;
html,
body {
border: 0;
margin: 0;
height: 100%;
min-height: 100%;
}
.container {
width: 100% !important;
}
#background {
width: 100%;
height: 100%;
}
&#13;
<div id="background">
</div>
&#13;
答案 1 :(得分:2)
在超时后10秒内清除间隔
试试这个:
var i = 0;
function change() {
var doc = document.getElementById("background");
var color = ["black", "blue", "brown", "green", "red", "yellow", "white", "pink", "purple", "orange"];
doc.style.backgroundColor = color[i];
i = (i + 1) % color.length;
}
myVar = setInterval(change, 1000);
setTimeout(() => {
clearInterval(myVar);
}, 10000);
html,
body {
border: 0;
margin: 0;
height: 100%;
min-height: 100%;
}
.container {
width: 100% !important;
}
#background {
width: 100%;
height: 100%;
}
<div id="background">
</div>
答案 2 :(得分:1)
setTimeout(function () {
clearInterval(myVar)
}, 10000)