2016-03-01 49 views
2

我目前正在記事本上工作,但錯誤不斷髮生。我的代碼有什麼問題?我正在嘗試使用對象數組打開交通燈。這是一個通過數組來完成的義務。交通燈onload功能

<html> 

<body onload="loop()"> 
<div style="background:black;width:75px;height:140px;margin:auto;"> 
<div id ="red" style="background:red;width:40px;height:40px;border-radius:40px;margin:auto;"></div> 
     <div id = "yellow" style="background:#3F4A00;width:40px;height:40px;border-radius:40px;margin:auto"></div> 
     <div id = "green" style="background:#044A00;width:40px;height:40px;border-radius:40px;margin:auto"></div> 
    <!--The style refers to css, the background --> 
    </div> 
    <script> 
    var redlight = document.getElementById('redlight'); 
    var yellowlight = document.getElementById('yellowlight'); 
    var greenlight = document.getElementById('greenlight'); 
    var colors = ["rgb(255, 0, 0)",'rgb(82, 2, 2)','rgb(255, 255, 0)','rgb(63, 74, 0)','rgb(0, 128, 0)','rgb(4, 74, 0)']; 
function loop() { 

    if (redlight.style.backgroundColor == colors[0]){ 
     redlight.style.backgroundColor = colors[1]; //switch off red 
     yellowlight.style.backgroundColor = colors[2]; //switch on yellow 
    } 
    else if (yellowlight.style.backgroundColor == colors[2]) { 
     yellowlight.style.backgroundColor = colors[3]; //switch off yellow 
     greenlight.style.backgroundColor = colors[4]; //switch on green 
    } 
    else if (greenlight.style.backgroundColor == colors[4]) { 
     greenlight.style.backgroundColor = colors[5]; //switch off green 
     redlight.style.backgroundColor = colors[0]; //switch on red 
    } 
      setInterval(function() { 
},3000); //this sets the intervals for each traffic light to change colors 
} 
</script> 
</body> 
</html> 

回答

0

你正在做的getElementById像

var redlight = document.getElementById('redlight'); 
var yellowlight = document.getElementById('yellowlight'); 
var greenlight = document.getElementById('greenlight'); 

和你的div有IDS:紅,黃,綠

<div id ="red" style="background:red;width:40px;height:40px;border-radius:40px;margin:auto;"></div> 
<div id = "yellow" style="background:#3F4A00;width:40px;height:40px;border-radius:40px;margin:auto"></div> 
<div id = "green" style="background:#044A00;width:40px;height:40px;border-radius:40px;margin:auto"></div> 

更改div編號至紅燈,yellowlight和綠燈。

<div id ="redlight" style="background:red;width:40px;height:40px;border-radius:40px;margin:auto;"></div> 
<div id = "yellowlight" style="background:#3F4A00;width:40px;height:40px;border-radius:40px;margin:auto"></div> 
<div id = "greenlight" style="background:#044A00;width:40px;height:40px;border-radius:40px;margin:auto"></div> 

另外

  1. 變化對紅燈爲背景色:#FF0000
  2. 動議的setInterval循環函數的外部。
  3. 將setInterval改爲setInterval(loop,3000);

這是一個工作js小提琴。 https://jsfiddle.net/n1b1htaz/1/

+0

Thak你我改變了,但它仍然不起作用? – Abass

+0

確定一秒。我會設置一個JS小提琴。 – kemiller2002

+0

oops紅色不起作用。多一秒。 – kemiller2002