如何使用Javascript使用一个按钮更改div的颜色?

时间:2015-10-05 14:26:40

标签: javascript html

我是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);
    };

1 个答案:

答案 0 :(得分: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>
&#13;
&#13;
&#13;