Javascript 编写的一个红、黄、绿灯交替变亮

为了创建一个简单但功能完整的交通灯程序,我们将使用 HTML、CSS 和 JavaScript 来实现红、黄、绿三种颜色按照规定的顺序循环显示。这个例子将确保灯光按照红 -> 绿 -> 黄的顺序循环,并且可以调整每个灯光的持续时间以模拟真实的交通灯行为。

效果图

源代码

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>交通灯</title>
<link rel="stylesheet" href="styles.css">
<style>
	body {
	    display: flex;
	    justify-content: center;
	    align-items: center;
	    height: 100vh;
	    margin: 0;
	    background-color: #f0f0f0;
	}
	
	.traffic-light {
	    width: 100px;
	    background-color: #222;
	    padding: 20px;
	    border-radius: 10px;
	}
	
	.light {
	    width: 60px;
	    height: 60px;
	    margin: 10px auto;
	    border-radius: 50%;
	    background-color: #ddd;
	    transition: background-color 0.3s;
	}
	
	#red-light.active { background-color: red; }
	#yellow-light.active { background-color: yellow; }
	#green-light.active { background-color: green; }
</style>
</head>
<body>
<div class="traffic-light">
    <div id="red-light" class="light"></div>
    <div id="yellow-light" class="light"></div>
    <div id="green-light" class="light"></div>
</div>

<script >
// 获取所有灯泡元素
const redLight = document.getElementById('red-light');
const yellowLight = document.getElementById('yellow-light');
const greenLight = document.getElementById('green-light');

// 定义一个函数来激活指定的灯泡
function activateLight(light) {
    // 移除所有灯泡的 active 类
    [redLight, yellowLight, greenLight].forEach(l => l.classList.remove('active'));
    
    // 给指定的灯泡添加 active 类
    light.classList.add('active');
}

// 定义交通灯的状态顺序
const lightSequence = [redLight, yellowLight, greenLight];

// 当前索引
let currentIndex = 0;

// 创建一个间隔计时器来切换灯光
function startTrafficLight() {
    setInterval(() => {
        // 激活当前索引对应的灯泡
        activateLight(lightSequence[currentIndex]);
        
        // 更新索引到下一个状态
        currentIndex = (currentIndex + 1) % lightSequence.length;
    }, 2000); // 每 2 秒切换一次
}

// 开始交通灯循环
startTrafficLight();
	
</script>
</body>
</html>
相关推荐
视图猿人5 小时前
RxJS基本使用及在next.js中使用的例子
开发语言·javascript
bitbitDown6 小时前
从零打造一个 Vite 脚手架工具:比你想象的简单多了
前端·javascript·面试
冴羽8 小时前
为什么在 JavaScript 中 NaN !== NaN?背后藏着 40 年的技术故事
前端·javascript·node.js
久爱@勿忘8 小时前
vue下载项目内静态文件
前端·javascript·vue.js
前端炒粉8 小时前
21.搜索二维矩阵 II
前端·javascript·算法·矩阵
不爱吃糖的程序媛8 小时前
Electron 应用中的系统检测方案对比
前端·javascript·electron
pe7er9 小时前
用高阶函数实现递归:从匿名函数到通用递归生成器
前端·javascript
Jonathan Star9 小时前
NestJS 是基于 Node.js 的渐进式后端框架,核心特点包括 **依赖注入、模块化架构、装饰器驱动、TypeScript 优先、与主流工具集成** 等
开发语言·javascript·node.js
矢心9 小时前
setTimeout 和 setInterval:看似简单,但你不知道的使用误区
前端·javascript·面试
一枚前端小能手9 小时前
🧭 使用历史记录 API - SPA导航与状态管理的完整指南
前端·javascript