.traffic-light {
  width: 100px;
  height: 300px;
  border: 1px solid black;
  position: relative;
}

.light {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin: 10px auto;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
  position: absolute;
  top: 10px;
  left: 10px;
}

.red {
  background-color: red;
}

.yellow {
  background-color: yellow;
  top: 100px;
}

.green {
  background-color: green;
  top: 190px;
}

.timer {
  margin-top: 20px;
  text-align: center;
}

.countdown {
  font-size: 30px;
  font-weight: bold;
}
const redTime = 30; // 红灯亮起的时间(秒)
const yellowTime = 3; // 黄灯亮起的时间(秒)
const greenTime = 30; // 绿灯亮起的时间(秒)

let countdown = 0; // 倒计时剩余时间

// 获取红绿黄灯元素
const redLight = document.querySelector('.red');
const yellowLight = document.querySelector('.yellow');
const greenLight = document.querySelector('.green');

// 获取倒计时元素
const countdownEl = document.querySelector('.countdown');

// 初始化红绿灯状态
redLight.classList.add('active');

// 开始倒计时
setInterval(() => {
  countdown--;

  // 更新倒计时元素内容
  countdownEl.textContent = countdown;

  // 判断倒计时是否结束
  if (countdown <= 0) {
    // 红灯亮起
    if (redLight.classList.contains('active')) {
      redLight.classList.remove('active');
      greenLight.classList.add('active');
      countdown = greenTime;
    }
    // 绿灯亮起
    else if (greenLight.classList.contains('active')) {
      greenLight.classList.remove('active');
      yellowLight.classList.add('active');
      countdown = yellowTime;
    }
    // 黄灯亮起
    else if (yellowLight.classList.contains('active')) {
      yellowLight.classList.remove('active');
      redLight.classList.add('active');
      countdown = redTime;
    }
  }
}, 1000);

效果如下图所示:

traffic-light

JavaScript 实现红绿灯效果:带倒计时功能

原文地址: https://www.cveoy.top/t/topic/oyAT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录