首页 > 解决方案 > 如果盒子是特定颜色的,我如何更改它的颜色?

问题描述

我是 JavaScript 新手,目前正在尝试一些东西。无论如何,我正在制作一个简单的盒子来改变onclick按钮的颜色。答案很简单,但我就是想不通。到目前为止,这是 HTML:

var btn = document.getElementById("btn");
var box = document.getElementById("box");

function changeColor() {
  box.style.backgroundColor = "red";
}

function ifColor() {
  if (box.style.backgroundColor == "red") {
    box.style.backgroundColor = "blue";
  }
}
#box {
  width: 200px;
  height: 200px;
  border-style: solid;
  border-width: 0.5px;
}
<div id="box"></div>
<button id="btn" onclick="changeColor(); ifColor();">
    Change box color
</button>

当我按下按钮时,它只会变成蓝色,当我再次按下它时,没有任何反应。如果我删除该ifColor功能,该按钮只会使框变为红色。

标签: javascripthtmlcss

解决方案


只需使用一种切换颜色的功能。

var btn = document.getElementById("btn");
var box = document.getElementById("box");

function changeColor() {
  if (box.style.backgroundColor == "blue") {
    box.style.backgroundColor = "red";
  } else {
    box.style.backgroundColor = "blue";
  }
}
#box {
  width: 200px;
  height: 200px;
  border-style: solid;
  border-width: 0.5px;
}
<div id="box"></div>
<button id="btn" onclick="changeColor();">
    Change box color
</button>


推荐阅读