我正在嘗試在閱讀「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)。然後... –