JS switch on click between colors with/ if else

JS switch onlick between two colors w/ if else

我正在处理我的作品集,需要在元素的样式状态之间切换。目前,我正试图让它在下面的例子中起作用。在这种特殊情况下,我的目标是单击按钮并在每次单击时在绿色和红色背景之间切换。但有些事情是行不通的。我可以从绿色切换到红色,但不能从红色切换到绿色。我错过了什么?

<button id="button">Toggle</button>
<div class="test" id="test"></div>


.test {
  width: 100px;
  height: 100px;
  background: green;
  margin-top: 20px;
}


var btn = document.getElementById("button");
var test = document.getElementById("test");

btn.onclick = function() {
  if (test.style.background = "green") {test.style.background = "red";} else {test.style.background = "green";}};

Codepen 演示 https://codepen.io/yanniksturm/pen/rNVmqJe

非常感谢!

在 if 条件下应该有双 (==) 等号,并且还通过 backgroundColor 而不是 background 检查,因为某些浏览器具有更多带有 background 的属性,例如 background: green none repeat scroll 0% 0%; 所以条件不会执行。
我建议使用 backgroundColor 而不是 background

var btn = document.getElementById("button");
var test = document.getElementById("test");

btn.onclick = function() {
  if (test.style.backgroundColor == "red") {
    test.style.backgroundColor = "green";} 
  else {
    test.style.backgroundColor = "red";
  }
}
.test {
  width: 100px;
  height: 100px;
  background: green;
  margin-top: 20px;
}
<button id="button">Toggle</button>
<div class="test" id="test"></div>