html通过时间函数,制作红绿灯倒计时
时间: 2023-12-30 08:24:04 浏览: 94
HTML本身并不支持时间函数,但可以通过JavaScript来实现红绿灯倒计时效果。下面是一个简单的示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>红绿灯倒计时</title>
<style>
.red {
background-color: red;
width: 100px;
height: 100px;
border-radius: 50%;
}
.yellow {
background-color: yellow;
width: 100px;
height: 100px;
border-radius: 50%;
}
.green {
background-color: green;
width: 100px;
height: 100px;
border-radius: 50%;
}
</style>
</head>
<body>
<div id="traffic-light">
<div class="red"></div>
<div class="yellow"></div>
<div class="green"></div>
</div>
<script>
function changeLight() {
var red = document.querySelector('.red');
var yellow = document.querySelector('.yellow');
var green = document.querySelector('.green');
red.style.backgroundColor = 'red';
yellow.style.backgroundColor = 'gray';
green.style.backgroundColor = 'gray';
setTimeout(function() {
red.style.backgroundColor = 'gray';
yellow.style.backgroundColor = 'yellow';
green.style.backgroundColor = 'gray';
setTimeout(function() {
red.style.backgroundColor = 'gray';
yellow.style.backgroundColor = 'gray';
green.style.backgroundColor = 'green';
setTimeout(function() {
red.style.backgroundColor = 'red';
yellow.style.backgroundColor = 'gray';
green.style.backgroundColor = 'gray';
changeLight();
}, 2000);
}, 2000);
}, 2000);
}
changeLight();
</script>
</body>
</html>
```
这段代码会在页面上创建一个红绿灯的效果,每个灯的颜色会根据倒计时进行变化。通过使用`setTimeout`函数,可以实现定时改变灯的颜色,从而实现红绿灯的倒计时效果。
阅读全文