xinyang

前言

用js实现红绿灯


提示:以下是本篇文章正文内容,下面案例可供参考

一、红绿灯

示例:通过定时器、flag标记实现倒计时以及红绿灯的切换。

二、使用步骤

1.定义flag标记

var flag=1; //初始为1,‘1’代表红灯 ‘2’代表绿灯 ‘3’代表黄灯
代码如下(示例):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        ul{
            width: 400px;
            height: 300px;
            margin: 60px auto;
        }
        li{
            display: block;
            border-radius: 50%;
            width: 80px;
            height: 80px;
            margin-left: 10px;
            float: left;
            background-color:gray;
        }
        #time{
            width: 80px;
            height: 80px;
            margin-left: 20px;
            background-color:black;
            float: left;
            font-size: 60px;
            color: rgb(248, 15, 15);
            font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
            text-align: center;
            line-height: 80px;
        }
    </style>
</head>
<body>
    <div class="main">
        <ul><li id="red"></li>
            <li id="yellow"></li>
            <li id="green"></li>
            <div id="time"></div>
        </ul>
        </div>
    </div>
</body>
<script>
    var now=30;
    var flag=1;             //初始为1,‘1’代表红灯 ‘2’代表绿灯 ‘3’代表黄灯
    function fun(){
        document.getElementById("time").innerHTML=now--;
        console.log(now);
    //控制红灯
    if(flag==1){
            if(now>=0)
                document.getElementById("red").style.backgroundColor="red";
            else{
                now=3;
                flag=2;
                document.getElementById("red").style.backgroundColor="gray"
            }
        }
    //控制黄灯
    if(flag==2){
        if(now>=0)
            document.getElementById("yellow").style.backgroundColor="yellow";
            else{
                now=30;
                flag=3;
                document.getElementById("yellow").style.backgroundColor="gray"
            }
    }
    //控制绿灯
    if(flag==3){
        if(now>=0)
            document.getElementById("green").style.backgroundColor="green";
            else{
                now=5;
                flag=1;
                document.getElementById("green").style.backgroundColor="gray"
                 //加处理 当一次红黄绿结束后 绿灯变灰灯时需要立即把红灯点亮
                document.getElementById("red").style.backgroundColor="red";        
            }
    }
    }
    fun();
    setInterval(fun,1000);
</script>
</html>

ps:功能基本实现,但是性能上肯定不好,还有其他实现的方法,希望大佬们赐教!!!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐