2015-10-05 185 views
-2

我對Javascript很新,所以請隨時指出我做錯的任何事情。我試圖每次點擊按鈕時更改div的顏色。這是我的代碼到目前爲止:如何使用Javascript更改一個按鈕的div的顏色?

function setBgColour(){ 
     if (.backgroundColor == '#ff0000'){ 
      document.getElementsByClassName("light")[0].style.backgroundColor = '#ffff00'; 
     } else if (.backgroundColor == '#ffff00'){ 
      document.getElementsByClassName("light")[0].style.backgroundColor = '#00ff00' 
     } else if (.backgroundColor == '#00ff00'){ 
      document.getElementsByClassName("light")[0].style.backgroundColor = '#ff0000' 
     } 
    } 

    window.onload = function(){ 
     document.getElementById('next').addEventListener('click', setBgColour); 
    }; 
+0

會是更好的存儲陣列中的顏色?並通過它們循環 – Dale

+0

刪除if中的點。 –

+0

除非有理由不這樣做。我建議你開始使用jQuery。它使JavaScript變得更容易。 – Jay

回答

1

問題是與您的條件聲明。你正在做的:

if (.backgroundColor == '#ff0000') 

什麼是你正在尋找進入元素,以獲得backgroundColor財產?

你應該這樣做:

window.onload = function() { 
 
    var current = '#ff0000'; 
 

 
    function setBgColour() { 
 
    var light = document.getElementsByClassName("light")[0]; 
 
    if (current == '#ff0000') { 
 
     current = '#ffff00'; 
 
    } else if (current == '#ffff00') { 
 
     current = '#00ff00'; 
 
    } else if (current == '#00ff00') { 
 
     current = '#ff0000'; 
 
    } 
 

 
    light.style.backgroundColor = current; 
 
    } 
 

 
    document.getElementById('next').addEventListener('click', setBgColour); 
 
    setBgColour(); 
 
};
.light { 
 
    width: 100px; 
 
    height: 100px; 
 
}
<div class="light"></div> 
 
<button id="next">Next</button>

+0

啊,非常感謝。我明白我現在出錯了 – Dale