<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>交通灯计时器</title>
</head>
<body>
<style>
/* 交通灯圆圈的样式 */
span {
display: inline-block;
width: 80px;
height: 80px;
border-radius: 50%;
border: 1px solid white;
opacity: 0.1;
}
/* 高亮显示当前亮起的灯 */
.light{
opacity: 1;
}
/* 红灯的样式 */
#red{
background-color: red;
}
/* 黄灯的样式 */
#yellow{
background-color: yellow;
}
/* 绿灯的样式 */
#green{
background-color: green;
}
/* 计时器显示的样式 */
#time{
margin-left: 30px;
font-size: 70px;
}
</style>
<!-- 交通灯和计时器元素 -->
<p>
<span id="red" class="light"></span>
<span id="yellow"></span>
<span id="green"></span>
<b id="time">10</b>
</p>
<script>
// 初始化当前灯和计时器的变量
var current = 'red';
var time = 10;
// 切换亮起的灯并重置计时器的函数
function changeLight(from, to, timeout){
// 检查计时器是否在运行
if (time > 0) {
return;
}
// 更新当前灯并重置计时器
current = to;
time = timeout;
// 更新样式以反映亮起的灯的变化
document.getElementById(from).removeAttribute('class', 'light');
document.getElementById(to).setAttribute('class', 'light');
}
// 设置一个定时器来更新交通灯和计时器的显示
setInterval(function(){
// 减少计时器的计数
time--;
// 检查当前灯并在计时器达到0时切换到下一个灯
if (current === 'red') {
changeLight('red', 'yellow', 3);
} else if (current === 'yellow') {
changeLight('yellow', 'green', 8);
} else if (current === 'green'){
changeLight('green', 'red', 10);
}
// 更新计时器显示
document.getElementById('time').innerText = time;
}, 1000);
</script>
</body>
</html>