利用js實現簡易紅綠燈
阿新 • • 發佈:2020-10-17
HTML程式碼:
在一個div容器內,設定3個span
<body> <div id="i1"> <span class="light red_light"></span> <span class="light yellow_light"></span> <span class="light green_light"></span> </div>
CSS程式碼:
<style> .red_light { width: 200px; height: 200px; border-radius: 50%; margin-left: 10px; display: inline-block; background-color: red; } .yellow_light { width: 200px; height: 200px; border-radius: 50%; margin-left: 10px; display: inline-block; background-color: yellow; } .green_light { width: 200px; height: 200px; border-radius: 50%; margin-left: 10px; display: inline-block; background-color: green; } .light { width: 200px; height: 200px; background-color: #777777; border-radius: 50%; margin-left: 10px; display: inline-block; } #i1 { width: 660px; height: 200px; margin: 0 auto; border: black 10px solid; } </style>
JS程式碼
<script> function l() { r_l()//紅燈亮 setTimeout(y_l,1000);//黃燈一秒後亮 setTimeout(r_l,1000);//黃燈亮的同時關閉紅燈 setTimeout(g_l,2000);//綠燈兩秒後亮 setTimeout(y_l,2000);//綠燈亮,黃燈熄 setTimeout(g_l,3000);//三秒後,紅燈熄 } function r_l() { //獲取紅燈 let r = document.getElementsByClassName('red_light')[0]; //toggle函式,如果有該屬性,則去除,沒有該屬性,則新增 r.classList.toggle('light') } function g_l() { //同上 let r = document.getElementsByClassName('green_light')[0]; r.classList.toggle('light') } function y_l() { //同上 let r = document.getElementsByClassName('yellow_light')[0]; r.classList.toggle('light') } //紅燈10秒,黃燈2秒,綠燈10秒 l(); //先執行函式 window.onload = function () { t1 = setInterval(l,3000)//每隔三秒重複執行函式 }; //每隔三秒的時間是因為每個燈各閃一秒,如果改變了燈的持續時間,迴圈時間也要修改 </script>
執行效果
以上就是利用js實現簡易紅綠燈的詳細內容,更多關於js 實現紅綠燈的資料請關注我們其它相關文章!