交通灯上载功能

时间:2016-02-22 20:20:23

标签: javascript html css

因此,对于我的课程作业,我必须自动生成一个没有任何输入的交通信号灯,这使我进入javascript中的onload函数,该函数在加载页面时运行脚本。我想知道如何在我当前的代码中正确实现它。我还希望交通灯在时间延迟的情况下循环通过颜色,这可以通过设定的间隔来完成。我正在努力正确地添加这两个功能以使其工作。我之前重用了css代码。 HTML

!important

CSS

<!DOCTYPE HTML>
<html>
<head>
<title> Traffic Light Script </title> <!-- Name for the above tab -->
<link href="TrafficCascade.css" rel="stylesheet">
</head>
<body onload="functionary()">   
<h1> Traffic Light </h1><!-- -->
<table> <!-- -->
<tr>
<td>
<div id="redL"></div>
<div id="yellowL"></div>
<div id="greenL"></div>
</td>
</tr>
</table>
<script src="gogled.js"></script>
</body>
</html>

的Javascript

#redL{
height: 50px;
width: 50px;
margin: 1px auto;
background-color: #7A0000;
border-radius: 50px;
border: solid 1px black;
padding: 1px;
}
#yellowL{
height: 50px;
width: 50px;
margin: 1px auto;
background-color: #7A5C00;
border-radius: 50px; 
border: solid 1px black;
padding: 1px;
}
#greenL{
height: 50px;
width: 50px;
margin: 1px auto;
background-color: #008000;
border-radius: 50px;
border: solid 1px black;
padding: 1px;
}
table{         /* Doesn't need dashes */
height: 180px;
width: 80px;
background-color: #000000;
border: 1px #000000;
text-align: center; 
margin-left: 50%; /* makes margin right 50% */
padding: 1px;
}
h1{
text-align: center;
padding: 1px;
}

1 个答案:

答案 0 :(得分:0)

我将你的setInterval移到了你的职能之外。 body元素调用函数onload。每3000ms setInterval调用该函数。

<强> JS:

var time = 5;

function functionary() {
  var red = document.getElementById('redL')
  var yellow = document.getElementById('yellowL')
  var green = document.getElementById('greenL')
  var Colours = ["#FF0000", "#FFB300", "#05FF0D", "#7A0000", "#7A5C00", "#008000"];
  if (time == 5) {
    red.style.background = Colours[0]; // May need spacebar between index number
    yellow.style.background = Colours[4];
    green.style.background = Colours[5];
    time = 1;
  } else if (time == 2 || time == 4) {
    red.style.background = Colours[3];
    yellow.style.background = Colours[1];
    green.style.background = Colours[5];
  } else if (time == 3) {
    red.style.background = Colours[3];
    yellow.style.background = Colours[4];
    green.style.background = Colours[2];
  }
  time += 1;
};
setInterval(function() {
  functionary();
}, 3000);

演示: https://jsfiddle.net/hopkins_matt/adv7exap/

相关问题