红绿灯html js
时间: 2024-02-23 08:54:03 浏览: 72
以下是一个使用HTML和JavaScript实现红绿灯效果的示例:
```html
<!DOCTYPE html>
<html>
<head>
<style>
.light {
width: 50px;
height: 50px;
border-radius: 50%;
margin: 10px; }
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
.green {
background-color: green;
}
</style>
</head>
<body>
<div class="light red"></div>
<div class="light yellow"></div>
<div class="light green"></div>
<script>
function changeLights() {
var lights = document.getElementsByClassName("light");
var redLight = lights[0];
var yellowLight = lights[1];
var greenLight = lights[2];
setTimeout(function() {
redLight.classList.add("red");
yellowLight.classList.remove("yellow");
greenLight.classList.remove("green");
}, 3000);
setTimeout(function() {
redLight.classList.remove("red");
yellowLight.classList.add("yellow");
greenLight.classList.remove("green");
}, 6000);
setTimeout(function() {
redLight.classList.remove("red");
yellowLight.classList.remove("yellow");
greenLight.classList.add("green");
}, 9000);
setTimeout(changeLights, 12000);
}
changeLights();
</script>
</body>
</html>
```
这段代码会创建一个红绿灯的效果,红灯亮3秒,黄灯亮3秒,绿灯亮3秒,然后循环重复。通过JavaScript的定时器技术,我们可以控制每个灯的显示和隐藏。点击红色按钮可以关闭红绿灯效果,点击绿色按钮可以重新打开红绿灯效果。
阅读全文