如果盒子是特定颜色,如何更改盒子的颜色?

时间:2020-02-21 23:27:04

标签: javascript html css

我是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函数,则该按钮将使该框仅变为红色。

4 个答案:

答案 0 :(得分:1)

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

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>

答案 1 :(得分:0)

您的代码正在运行,只需将其延迟设置几秒钟即可查看其更改。

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

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

function ifColor() {
setTimeout(()=>{
 if (box.style.backgroundColor == "red") {
    box.style.backgroundColor = "blue";
  }
},2000);
 
}
#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>

答案 2 :(得分:0)

您是否想拥有它,当您单击按钮时,它会在红色和蓝色之间改变颜色?

设置代码的方式始终是蓝色的,因为:

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

function ifColor() {
  if (box.style.backgroundColor == "red") {
    box.style.backgroundColor = "blue";
  }
}

您首先调用changeColor();将按钮变为红色,然后运行ifColor(),将按钮更改为蓝色。这几乎是瞬间发生的。

您只需要这样做:

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

答案 3 :(得分:0)

您还可以执行以下操作:

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

function changeColor() {
  if (box.classList.contains('red')) {
    box.classList.remove('red');
    box.classList.add('blue');
  } else {
    box.classList.remove('blue');
    box.classList.add('red');
  }
}
#box {
  width: 200px;
  height: 200px;
  border-style: solid;
  border-width: 0.5px;
}

.red {
  background-color: red;
}

.blue {
  background-color: blue;
}
<div id="box" class="red"></div>
<button id="btn" onclick="changeColor();">
    Change box color
</button>