使用JavaScript编写一个令人惊叹的交通信号灯程序

40 min read

以下是一个简单的红绿灯程序,使用 JavaScript 编写:

<!DOCTYPE html>
<html>
<head>
	<title>JavaScript Traffic Light</title>
</head>
<body>
	<h1>JavaScript Traffic Light</h1>

	<div id="container">
		<div class="light red"></div>
		<div class="light yellow"></div>
		<div class="light green"></div>
	</div>

	<script>
		var redLight = document.querySelector('.red');
		var yellowLight = document.querySelector('.yellow');
		var greenLight = document.querySelector('.green');

		function switchLights() {
			setTimeout(function() {
				// Turn off red light and turn on yellow light
				redLight.classList.remove('active');
				yellowLight.classList.add('active');

				setTimeout(function() {
					// Turn off yellow light and turn on green light
					yellowLight.classList.remove('active');
					greenLight.classList.add('active');

					setTimeout(function() {
						// Turn off green light and turn on yellow light
						greenLight.classList.remove('active');
						yellowLight.classList.add('active');

						setTimeout(function() {
							// Turn off yellow light and turn on red light
							yellowLight.classList.remove('active');
							redLight.classList.add('active');

							// Start the process over again
							switchLights();
						}, 2000);
					}, 3000);
				}, 2000);
			}, 3000);
		}

		switchLights();
	</script>

	<style>
		#container {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 400px;
		}

		.light {
			width: 50px;
			height: 50px;
			border-radius: 50%;
			margin: 20px;
			box-shadow: 0 0 10px #000;
			transition: background-color 0.5s;
		}

		.red {
			background-color: #f00;
		}

		.yellow {
			background-color: #ff0;
		}

		.green {
			background-color: #0f0;
		}

		.active {
			box-shadow: 0 0 20px #000;
		}
	</style>
</body>
</html>

这个程序使用了 HTML、CSS 和 JavaScript 来创建一个简单的红绿灯交通信号系统。在 HTML 中,我们创建了一个包含红、黄、绿灯的容器。在 CSS 中,我们定义了灯的样式和动画。在 JavaScript 中,我们定义了一个函数 switchLights(),它在一段时间后切换灯的状态,并在每个状态之间延迟一定的时间。在最后,我们调用 switchLights() 函数来启动整个交通信号系统。

这只是一个简单的例子,它没有考虑到真实的交通信号系统中需要考虑的因素。但这个例子可以帮助你理解如何使用 JavaScript 创建一个动态的页面效果。