利用js實現簡易紅綠燈
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 實現紅綠燈的資料請關注好吧啦網其它相關文章!
相關文章:
