用html和css编写一个红绿灯,可手动点击切换颜色
时间: 2024-03-11 17:47:35 浏览: 22
好的,我可以帮你解答这个问题。
首先,我们可以使用HTML创建一个基本的红绿灯框架,包括三个圆形灯泡,如下所示:
```html
<div class="traffic-light">
<div class="bulb red"></div>
<div class="bulb yellow"></div>
<div class="bulb green"></div>
</div>
```
然后,我们可以使用CSS为红绿灯灯泡添加样式,并为其添加点击事件,如下所示:
```css
.traffic-light {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.bulb {
width: 100px;
height: 100px;
border-radius: 50%;
margin: 10px;
cursor: pointer;
}
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
.green {
background-color: green;
}
```
```javascript
var red = document.querySelector('.red');
var yellow = document.querySelector('.yellow');
var green = document.querySelector('.green');
red.addEventListener('click', function() {
red.classList.add('active');
yellow.classList.remove('active');
green.classList.remove('active');
});
yellow.addEventListener('click', function() {
red.classList.remove('active');
yellow.classList.add('active');
green.classList.remove('active');
});
green.addEventListener('click', function() {
red.classList.remove('active');
yellow.classList.remove('active');
green.classList.add('active');
});
```
这段JavaScript代码将为每个灯泡添加点击事件,当点击红灯时,红灯点亮,黄灯和绿灯熄灭;当点击黄灯时,黄灯点亮,红灯和绿灯熄灭;当点击绿灯时,绿灯点亮,红灯和黄灯熄灭。
综上所述,这是一个简单的HTML+CSS+JavaScript可手动切换颜色的红绿灯示例。