利用js實(shí)現(xiàn)簡易紅綠燈
HTML代碼:
在一個div容器內(nèi),設(shè)置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);//黃燈亮的同時關(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ù) };//每隔三秒的時間是因?yàn)槊總€燈各閃一秒,如果改變了燈的持續(xù)時間,循環(huán)時間也要修改</script>
運(yùn)行效果

以上就是利用js實(shí)現(xiàn)簡易紅綠燈的詳細(xì)內(nèi)容,更多關(guān)于js 實(shí)現(xiàn)紅綠燈的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 理解PHP5中static和const關(guān)鍵字2. Android table布局開發(fā)實(shí)現(xiàn)簡單計算器3. jQuery 實(shí)現(xiàn)DOM元素拖拽交換位置的實(shí)例代碼4. IntelliJ IDEA安裝插件的方法步驟5. php模擬實(shí)現(xiàn)斗地主發(fā)牌6. vue 使用localstorage實(shí)現(xiàn)面包屑的操作7. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. Python random庫使用方法及異常處理方案9. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟10. Vuex localStorage的具體使用

網(wǎng)公網(wǎng)安備