利用js實(shí)現(xiàn)簡易紅綠燈
HTML代碼:
在一個(gè)div容器內(nèi),設(shè)置3個(gè)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);//黃燈亮的同時(shí)關(guān)閉紅燈 setTimeout(g_l, 2000);//綠燈兩秒后亮 setTimeout(y_l, 2000);//綠燈亮,黃燈熄 setTimeout(g_l, 3000);//三秒后,紅燈熄 } function r_l() { //獲取紅燈 let r = document.getElementsByClassName(’red_light’)[0]; //toggle函數(shù),如果有該屬性,則去除,沒有該屬性,則添加 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(); //先執(zhí)行函數(shù) window.onload = function () { t1 = setInterval(l, 3000)//每隔三秒重復(fù)執(zhí)行函數(shù) };//每隔三秒的時(shí)間是因?yàn)槊總€(gè)燈各閃一秒,如果改變了燈的持續(xù)時(shí)間,循環(huán)時(shí)間也要修改</script>
運(yùn)行效果
以上就是利用js實(shí)現(xiàn)簡易紅綠燈的詳細(xì)內(nèi)容,更多關(guān)于js 實(shí)現(xiàn)紅綠燈的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問題2. SpringBoot+TestNG單元測試的實(shí)現(xiàn)3. Springboot 全局日期格式化處理的實(shí)現(xiàn)4. idea配置jdk的操作方法5. Docker容器如何更新打包并上傳到阿里云6. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法7. VMware中如何安裝Ubuntu8. python 浮點(diǎn)數(shù)四舍五入需要注意的地方9. JAMon(Java Application Monitor)備忘記10. vue實(shí)現(xiàn)web在線聊天功能
