使用css寫一個紅綠燈交替的動畫效果

王铁柱6發表於2024-12-06
.traffic-light {
  width: 50px;
  height: 150px;
  border: 5px solid black;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin: 50px auto; /* Center the traffic light */
}

.light {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin: 5px auto;
  background-color: #333; /* Initially all lights are off (dark gray) */
}

.red {
  background-color: red;
  animation: redLight 10s infinite;
}

.yellow {
  background-color: yellow;
  animation: yellowLight 10s infinite;
}

.green {
  background-color: green;
  animation: greenLight 10s infinite;
}


@keyframes redLight {
  0%, 70% { background-color: red; } /* Red for 7 seconds */
  70.01%, 100% { background-color: #333; } /* Off for 3 seconds*/
}

@keyframes yellowLight {
  70%, 75% { background-color: yellow; } /* Yellow for 0.5 seconds */
  0%, 70%, 75.01%, 100% { background-color: #333; } /* Off for the rest */
}

@keyframes greenLight {
  75%, 100% { background-color: green; } /* Green for 2.5 seconds */
  0%, 75% { background-color: #333; } /* Off for the rest */
}

<!DOCTYPE html>
<html>
<head>
<title>Traffic Light</title>
<link rel="stylesheet" href="style.css"> </head>
<body>

<div class="traffic-light">
  <div class="light red"></div>
  <div class="light yellow"></div>
  <div class="light green"></div>
</div>

</body>
</html>

Explanation and Key Improvements:

  • Clearer Timing with Percentages: The animation keyframes now use percentages for more precise timing control, making the light sequence (Red -> Yellow -> Green) more obvious. The total cycle is 10 seconds.
  • #333 for "Off" State: Instead of completely transparent, the "off" state uses a dark gray (#333). This makes it visually clearer that the lights are part of the traffic light even when they're not illuminated.
  • CSS Classes for Styling and Animation: The CSS is structured with classes, making it more organized and maintainable. .traffic-light styles the container, .light styles the individual lights, and .red, .yellow, .green apply the colors and animations.
  • Simplified HTML: The HTML is straightforward, just a container div and three light divs inside.
  • Centering: Added margin: 50px auto; to center the traffic light on the page.

How it works:

  1. HTML Structure: The HTML sets up the three lights within the traffic light container.
  2. CSS Styling: The CSS provides basic styling like size, shape, and initial colors.
  3. CSS Animations: The @keyframes rules define the animation cycles for each light. They control when the background color changes to create the on/off effect. The animation property within each light's class applies the corresponding animation.

This improved code provides a more accurate and visually appealing traffic light animation. Remember to save the CSS as style.css and link it to your HTML file.

相關文章