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>

在css中,light在后面,所以后面变换颜色通过的是 classList.toggle('light')

此时的效果

scipt代码:

 

<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>
View Code

 

 

 

效果图:

 

转载于:https://www.cnblogs.com/98WDJ/p/10685559.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值