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);
``
weba编写HTML设置红黄绿灯及倒计时的显示页面。b创建红、黄、绿灯对象lamp保存相关的数据。c创建倒计时的元素对象count实现倒计时的时间设置。d根据lamp和count对象获取并设置绿灯亮时页面初始化效果。e利用setInterval函数完成信号灯倒计时的动态改变效果。

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

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