JavaScript背景颜色切换

时间:2019-12-14 22:36:05

标签: javascript

enter image description here

我有一个简单的功能,只是将按钮的背景色从浅绿色转换为红色,然后再次转换为红色。但是,当我调用此函数时,它所做的只是将其更改为红色,我不确定为什么。我在这里看过其他类似的例子,我觉得我做得正确。希望有帮助!

<button id = "button1" onclick="myFunction()">This is a button</button>

    button {
    background-color: Aqua;
}

function myFunction() {
  if (document.getElementById("button1").style.backgroundColor === "Aqua"){
    document.getElementById("button1").style.backgroundColor = "Red";
    document.getElementById("button1").innerHTML = "I'm RED!!";
  } else { 
    document.getElementById("button1").style.backgroundColor = "Aqua";
    document.getElementById("button1").innerHTML = "I'm back BABY!!";
  }  
}

3 个答案:

答案 0 :(得分:0)

它是这样的

if ($("#yourselector").css('background-color')=="rgb(220, 
20, 60)") alert("matched");

您需要将名称转换为红色,绿色,蓝色组件,您可以使用此工具

http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php

答案 1 :(得分:0)

最简单的方法是将this传递到您的onclick()函数中,并使用三元运算符确定切换状态。

function myFunction(btn) {
  const isRed = btn.style.backgroundColor === "red";
  btn.style.backgroundColor = isRed ? "aqua" : "red";
  btn.innerHTML = isRed ? "I'm back BABY!!" : "I'm RED!!";
}
button {
  background-color: aqua;
}
<button id="button1" onclick="myFunction(this)">This is a button</button>

答案 2 :(得分:-1)

第一个if语句应具有小写aqua ..如下所示

function myFunction() {
if (document.getElementById("button1").style.backgroundColor === "aqua") {
    document.getElementById("button1").style.backgroundColor = "red";
    document.getElementById("button1").innerHTML = "I'm RED!!";
} else {
    document.getElementById("button1").style.backgroundColor = "aqua";
    document.getElementById("button1").innerHTML = "I'm back BABY!!";
}

}

我通过做发现了     console.log(document.getElementById(“ button1”)。style);在日志中,您将拥有可以展开的对象,并发现css选择器为小写字母, 也将红色设为相同以避免混淆。

希望有帮助