在我原来代码上,把js定时器改成用for循环优化

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>

<script>
 window.onload=function(){
 var btn1 = document.getElementById("btn1");
 var btn2 = document.getElementById("btn2");
 var btn3 = document.getElementById("btn3");
 var btn4 = document.getElementById("btn4");
 var btn5 = document.getElementById("btn5");
//  
 setTimeout(time1,2000);
 function time1(){
//        
 btn1.style.backgroundColor = "red";
 btn2.style.backgroundColor = "#000";
 btn3.style.backgroundColor = "#000";
 btn4.style.backgroundColor = "#000";
 btn5.style.backgroundColor = "#000";
        }

 setTimeout(time2,4000);
 function time2(){
 btn1.style.backgroundColor = "#000";
 btn2.style.backgroundColor = "red";
 btn3.style.backgroundColor = "#000";
 btn4.style.backgroundColor = "#000";
 btn5.style.backgroundColor = "#000";
        }
 setTimeout(time3,6000);
 function time3(){
 btn1.style.backgroundColor = "#000";
 btn2.style.backgroundColor = "#000";
 btn3.style.backgroundColor = "red";
 btn4.style.backgroundColor = "#000";
 btn5.style.backgroundColor = "#000";
        }
 setTimeout(time4,8000);
 function time4(){
 btn1.style.backgroundColor = "#000";
 btn2.style.backgroundColor = "#000";
 btn3.style.backgroundColor = "#000";
 btn4.style.backgroundColor = "red";
 btn5.style.backgroundColor = "#000";
        }
 setTimeout(time5,10000);
 function time5(){
 btn1.style.backgroundColor = "#000";
 btn2.style.backgroundColor = "#000";
 btn3.style.backgroundColor = "#000";
 btn4.style.backgroundColor = "#000";
 btn5.style.backgroundColor = "red";
        }
    }
</script>
<style>
 li{
        width: 100px;
 height: 100px;
 background-color: #000;
 }
</style>
<body>
<div>
    <ol>
        <li id="btn1"></li>
        <li id="btn2"></li>
        <li id="btn3"></li>
        <li id="btn4"></li>
        <li id="btn5"></li>
    </ol>
</div>
</body>
</html>


林夕plus
浏览 1785回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP