服务器之家:专注于服务器技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - 利用js实现简易红绿灯

利用js实现简易红绿灯

2021-10-26 15:44日天达人 JavaScript

这篇文章主要介绍了利用js实现简易红绿灯,帮助大家更好的利用js制作特效,美化网页,感兴趣的朋友可以了解下

HTML代码:

在一个div容器内,设置3个span

?
1
2
3
4
5
6
7
<body>
<div id="i1">
  <span class="light red_light"></span>
  <span class="light yellow_light"></span>
  <span class="light green_light"></span>
 
</div>

CSS代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<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代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<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实现简易红绿灯的详细内容,更多关于js 实现红绿灯的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/98WDJ/p/10685559.html#4527173

延伸 · 阅读

精彩推荐