我正在尝试在阅读“for循环内的多个setTimeout调用”和“JavaScript闭合内部循环 - 简单的实例”之后,在实践中关闭和setTimeout。multiple setTimeout延迟修改CSS
在我的html中,我有10个div,每个人都有自己的课程。唯一的区别是backgroundColor。 CSS链接在html中。
我想要做的是在改变div的颜色之前应用延迟:div1/delay/div2/delay .....到目前为止,使用下面的代码,我只能改变所有的div颜色同一时间后,只有一个延迟。
感谢您的帮助,
<pre>
<!DOCTYPE
<html>
<head>
<link rel="stylesheet" type="text/css" href="mainCSS.css" title="compact" />
<script type="text/javascript">
var myVar; // setTimeout
var i=0; // index for css rules
var colorTab = ["red","blue","violet","black","yellow","green","DarkOrange","cyan","coral","silver"];
var colorTab = ["red","blue","violet","black","yellow","green","DarkOrange","cyan","coral","silver"];
function stop(){
clearTimeout(myVar);
}
function changeCSS(obj,numColor){
obj.style.backgroundColor=colorTab[numColor];
alert(numColor);
}
function getStyleSheet() {
var sheet = document.styleSheets[0];
var j=0;// index for colorTab
for(var i=0; i<sheet.cssRules.length-1;i++){
obj=sheet.cssRules[i];
(function(obj,j) {
var myVar=setTimeout(function() {changeCSS(obj,j);},500);
})(obj,j);
if (j==9){
j=0;
}else
{j=j+1;}
}
}
</script>
</head>
<body >
<p>
<button onclick="getStyleSheet()">GO</button><button onclick="stop()">STOP</button>
</p>
<div class="animate1" ></div><div class="animate2" ></div><div class="animate3"></div><div class="animate4"></div>
<div class="animate5" ></div><div class="animate6"></div><div class="animate7"></div><div class="animate8"></div><div class="animate9"></div><div class="animate10">
</div>
</body>
</html>
而CSS:
<pre>
div.animate1 {
width: 50px;
height: 50px;
position: ;
background-color: red;
}
div.animate2 {
width: 50px;
height: 50px;
position: ;
background-color: blue;
}
div.animate3 {
width: 50px;
height: 50px;
position: ;
background-color: violet;
}
div.animate4 {
width: 50px;
height: 50px;
position: ;
background-color: black;
}
div.animate5 {
width: 50px;
height: 50px;
position: ;
background-color:yellow;
}
div.animate6 {
width: 50px;
height: 50px;
position: ;
background-color: green;
}
div.animate7 {
width: 50px;
height: 50px;
position: ;
background-color: DarkOrange;
}
div.animate8 {
width: 50px;
height: 50px;
position: ;
background-color: cyan;
}
div.animate9 {
width: 50px;
height: 50px;
position: ;
background-color: coral;
}
div.animate10 {
width: 50px;
height: 50px;
position: ;
background-color: silver;
}
<code>
你需要以某种方式使这个产业链不是异步。你可以尝试在函数内部为第二个div调用setTimeout,为第一个div处理setTimeout,等等。并不擅长:)也可以使用Promises并使div1Handle.then(div2Handle)。然后... –