如何为此JavaScript和HTML代码添加一个按钮,以便当我按下按钮时,我的红绿灯序列会运行一次?

时间:2017-03-12 20:12:28

标签: javascript html html5 button

我想用用户输入(按钮)运行此代码,但我不知道如何操作。另外,我从互联网上获得了一些这样的代码,所以我仍然不太明白为什么颜色变量数组中有6种颜色,而不是只有3种颜色(红色,黄色,绿色)。我也不太了解if语句,所以如果你能解释为什么我真的需要var时间,那就太好了。谢谢!



var time = 5;

function lights() {
  var red = document.getElementById('redLight')
  var yellow = document.getElementById('yellowLight')
  var green = document.getElementById('greenLight')
  var Colours = ["#FF0000", "#FFB300", "#05FF0D", "#7A0000", "#7A5C00", "#008000"];
  if (time == 5) {
    red.style.background = Colours[0]; 
    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() {
  lights();
}, 2000);

  <h1> Traffic Light </h1>
        <div id="redLight"></div>
        <div id="yellowLight"></div>
        <div id="greenLight"></div>
        <div id="box"></div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

您可以添加<button onclick="test()"></button>按钮 然后你把间隔放在我称之为测试的函数中。喜欢: function test(){setInterval(lights(),2000)

答案 1 :(得分:0)

使用<button onclick=></button>。或者,您也可以使用<div> <div onclick=></div>进行onclick:private GradientDrawable imageButtonGradient() { GradientDrawable buttonShape = new GradientDrawable(); buttonShape.setCornerRadius(20); buttonShape.setColor(Color.WHITE); return buttonShape; }

答案 2 :(得分:0)

var time = 5;

function lights() {
  var red = document.getElementById('redLight')
  var yellow = document.getElementById('yellowLight')
  var green = document.getElementById('greenLight')
  var Colours = ["#FF0000", "#FFB300", "#05FF0D", "#7A0000", "#7A5C00", "#008000"];
  if (time == 5) {
    red.style.background = Colours[0]; 
    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() {
  lights();
}, 2000);
  <h1> Traffic Light </h1>
        <div id="redL"></div>
        <div id="yellowL"></div>
        <div id="greenL"></div>
        <div id="box"></div>

相关问题