用javascript,html css 实现
时间: 2024-03-25 13:41:40 浏览: 13
好的,我可以给你提供一个简单的交通信号灯倒计时的示例代码,你可以在此基础上进行修改和完善。以下是示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>交通信号灯倒计时</title>
<style>
#traffic-light {
width: 100px;
height: 300px;
background-color: black;
position: relative;
margin: 50px auto;
box-shadow: 0 0 30px rgba(255, 255, 0, 0.8);
}
.circle {
width: 80px;
height: 80px;
background-color: #333;
border-radius: 50%;
position: absolute;
top: 20px;
left: 10px;
right: 10px;
margin: auto;
box-shadow: 0 0 20px rgba(255, 255, 0, 0.8);
}
.circle.red {
background-color: #f00;
}
.circle.yellow {
background-color: #ff0;
}
.circle.green {
background-color: #0f0;
}
.timer {
font-size: 60px;
color: #fff;
text-align: center;
position: absolute;
top: 120px;
left: 0;
right: 0;
}
</style>
</head>
<body>
<div id="traffic-light">
<div class="circle red"></div>
<div class="circle yellow"></div>
<div class="circle green"></div>
<div class="timer"></div>
</div>
<script>
var timer = document.querySelector('.timer');
var circles = document.querySelectorAll('.circle');
var currentCircle = 0;
var remainingTime = 30; // 初始状态为红灯
function startTimer() {
if (remainingTime > 0) {
remainingTime--;
timer.textContent = remainingTime;
if (remainingTime === 0) {
switchLights();
}
}
}
function switchLights() {
circles[currentCircle].classList.remove('active');
currentCircle++;
if (currentCircle > 2) {
currentCircle = 0;
}
circles[currentCircle].classList.add('active');
switch (currentCircle) {
case 0:
remainingTime = 30;
break;
case 1:
remainingTime = 5;
break;
case 2:
remainingTime = 35;
break;
}
timer.textContent = remainingTime;
setTimeout(startTimer, 1000);
}
switchLights();
</script>
</body>
</html>
```
这段代码实现了交通信号灯的倒计时效果,使用了 HTML、CSS 和 JavaScript 技术。具体实现方法是通过 JavaScript 控制信号灯的显示和倒计时的变化,而使用 CSS 实现信号灯的样式。你可以根据自己的需求对代码进行修改和优化。