a) HTML 页面代码:

<!DOCTYPE html>
<html>
<head>
	<title>信号灯</title>
	<style>
		body{
			text-align:center;
		}
		h1{
			margin-top:50px;
		}
		.lamp{
			width:50px;
			height:50px;
			border-radius:50%;
			display:inline-block;
			margin:20px;
		}
		.red{
			background-color:red;
		}
		.yellow{
			background-color:yellow;
		}
		.green{
			background-color:green;
		}
		.count{
			font-size:30px;
			margin-top:50px;
		}
	</style>
</head>
<body>
	<h1>交通信号灯</h1>
	<div class='lamp red'></div>
	<div class='lamp yellow'></div>
	<div class='lamp green'></div>
	<div class='count'>倒计时:30秒</div>
	<script src='signal.js'></script>
</body>
</html>

b) JavaScript 代码:

var lamp = {
  red: document.querySelector('.red'),
  yellow: document.querySelector('.yellow'),
  green: document.querySelector('.green')
};

c) JavaScript 代码:

var count = {
  time: 30,
  element: document.querySelector('.count')
};

d) JavaScript 代码:

lamp.green.style.backgroundColor = 'green';
count.element.textContent = '倒计时:' + count.time + '秒';

e) JavaScript 代码:

setInterval(function() {
  if (count.time > 0) {
    count.time--;
    count.element.textContent = '倒计时:' + count.time + '秒';
  } else {
    count.time = 30;
    if (lamp.green.style.backgroundColor === 'green') {
      lamp.green.style.backgroundColor = '';
      lamp.yellow.style.backgroundColor = 'yellow';
    } else if (lamp.yellow.style.backgroundColor === 'yellow') {
      lamp.yellow.style.backgroundColor = '';
      lamp.red.style.backgroundColor = 'red';
    } else {
      lamp.red.style.backgroundColor = '';
      lamp.green.style.backgroundColor = 'green';
    }
  }
}, 1000);
HTML+JavaScript 实现交通信号灯倒计时效果

原文地址: https://www.cveoy.top/t/topic/obnU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录