前端 单标签 纯 CSS 实现红绿灯动画

使用一个div标签画出一个红绿灯并加上灯光切换的动画。 关键思想在于一个标签的box-shadow属性能够同时设置多个。css

效果以下:

代码:
html:
{
 <!--warp标签是后面的蓝色背景-->
  <div class="wrap">
    <div class="traffic-light"></div>
  </div>
}

css:
    body {
      margin: 0;
      /* 绝对定位使height: 100%生效 */
      position: absolute; 
      height: 100%;
      width: 100%;
    }
    /* 背景图 使用margin auto实现垂直水平居中 */
    .wrap {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
      width: 500px;
      height: 350px;
      background: rgb(97, 170, 189);
    }
    /* 灯框架 */
    .traffic-light {
      /* 居中代码 */
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
      text-align: center;

      /* 绘制图案 */
      width: 300px;
      height: 90px;
      background: #282f2f;
      border-radius: 50px;
      box-shadow: 0 0 0 2px #eee inset;
    }
    .traffic-light::after {
      /* 居中代码 */
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);

      content: '';
      display: inline-block;
      width: 70px;
      height: 70px;
      border-radius: 50%;

      animation: traffic-light 5s linear 0s infinite;
    }
    
    @keyframes traffic-light {
      from {
        background: transparent;  /* 黄灯 */

        box-shadow: 
          -85px 0 0 0 transparent,  /* 红灯 */
          85px 0 0 0 transparent, /* 绿灯 */
          -85px 0 15px 0 transparent, /* 红灯光影 */
          0px 0 15px 0 transparent, /* 黄灯光影 */
          85px 0 15px 0 transparent; /* 绿灯光影 */
      }
      25% {
        background: transparent;  /* 黄灯 */

        box-shadow: 
          -85px 0 0 0 rgb(247, 78, 26),  /* 红灯 */
          85px 0 0 0 transparent, /* 绿灯 */
          -85px 0 15px 0 rgb(247, 78, 26), /* 红灯光影 */
          0px 0 15px 0 transparent, /* 黄灯光影 */
          85px 0 15px 0 transparent; /* 绿灯光影 */
      }
      50% {
        background: rgb(231, 183, 78);  /* 黄灯 */

        box-shadow: 
          -85px 0 0 0 transparent,  /* 红灯 */
          85px 0 0 0 transparent, /* 绿灯 */
          -85px 0 15px 0 transparent, /* 红灯光影 */
          0px 0 15px 0 rgb(231, 183, 78), /* 黄灯光影 */
          85px 0 15px 0 transparent; /* 绿灯光影 */
      }
      75% {
        background: transparent;  /* 黄灯 */

        box-shadow: 
          -85px 0 0 0 transparent,  /* 红灯 */
          85px 0 0 0 rgb(38, 175, 84), /* 绿灯 */
          -85px 0 15px 0 transparent, /* 红灯光影 */
          0px 0 15px 0 transparent, /* 黄灯光影 */
          85px 0 15px 0 rgb(38, 175, 84); /* 绿灯光影 */
      }
      to {
        background: transparent;  /* 黄灯 */

        box-shadow: 
          -85px 0 0 0 transparent,  /* 红灯 */
          85px 0 0 0 transparent, /* 绿灯 */
          -85px 0 15px 0 transparent, /* 红灯光影 */
          0px 0 15px 0 transparent, /* 黄灯光影 */
          85px 0 15px 0 transparent; /* 绿灯光影 */
      }
    }
复制代码

完整代码地址:github.com/junhaogz215…html

相关文章
相关标签/搜索