You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何我的交通灯CSS动画无法正常运行?

修复交通灯依次亮起的CSS动画问题

你的代码存在几个核心问题,导致动画无法正常工作:

  • 错误使用color属性做动画:交通灯的“灯”是通过border实现的,color控制的是文本颜色(你的p标签是空的,完全无效),应该动画border-color。
  • 无分段激活逻辑:三个动画同时启动,没有设置依次亮起的时间段,自然不会呈现“依次点亮”的效果。
  • 初始状态不符合需求:border默认是白色,不符合交通灯未点亮时的暗态。
  • 关键帧逻辑混乱:当前的关键帧设置会让灯在多个节点反复变色,不符合依次亮起的需求。

修改后的完整代码

CSS

div {
  background-color: #000;
  border: 15px solid rgba(128, 119, 119, 0.88);
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column-reverse;
  width: 120px;
  height: 400px;
  box-sizing: border-box;
}

/* 统一灯的基础样式 */
.light {
  border: 40px solid #333; /* 未点亮时的深灰色 */
  border-radius: 50%;
  margin: 10px 0;
  animation-duration: 15s;
  animation-iteration-count: infinite; /* 循环播放 */
  animation-timing-function: step-end; /* 无过渡,直接切换颜色 */
}

/* 红灯动画:前1/3时间点亮 */
@keyframes redLight {
  0% { border-color: #333; }
  0.1%, 33.3% { border-color: red; }
  33.4%, 100% { border-color: #333; }
}

/* 黄灯动画:中间1/3时间点亮 */
@keyframes yellowLight {
  0%, 33.3% { border-color: #333; }
  33.4%, 66.6% { border-color: yellow; }
  66.7%, 100% { border-color: #333; }
}

/* 绿灯动画:最后1/3时间点亮 */
@keyframes greenLight {
  0%, 66.6% { border-color: #333; }
  66.7%, 100% { border-color: green; }
}

#c1 { animation-name: redLight; }
#c2 { animation-name: yellowLight; }
#c3 { animation-name: greenLight; }

HTML

<div>
  <p id="c1" class="light"></p>
  <p id="c2" class="light"></p>
  <p id="c3" class="light"></p>
</div>

关键修改说明

  1. 动画目标修正:将动画属性从color改为border-color,直接控制灯的边框颜色(也就是灯的显示颜色)。
  2. 统一基础样式:给所有灯添加.light类,减少重复代码,初始设为深灰色代表未点亮状态。
  3. 分段关键帧设计:把15秒的总时长分成三段,每个灯在对应时间段点亮,实现依次亮起的效果。
  4. 优化布局:调整容器的宽高和padding,让交通灯更贴近真实比例,使用box-sizing: border-box避免padding撑大容器。
  5. 循环与切换效果:设置animation-iteration-count: infinite让动画循环播放,step-end让颜色切换更干脆,模拟真实交通灯的切换逻辑。

内容的提问来源于stack exchange,提问作者Adam Zahir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 08:13:24