使用 "If statement" 获取 Javascript 中彩色文本的值

Using an "If statement" to get the value of the coloured text in Javascript

我正在尝试做一个东西,当你点击一个按钮时,文本会变成绿色,如果你再次点击它,文本会变成蓝色。我这样做的策略是测试文本是绿色还是蓝色,但我不知道如何:

var topcon = document.getElementsByClassName("topchoice");

function show() {
    if(topcon.style.color = "blue") {
        for (count=0; count < topcon.length; count++) {
        topcon[count].style.color = "green";
        }
    }
    else if(topcon.style.color = "green") {
        for (count=0; count < topcon.length; count++) {
            topcon[count].style.color = "blue";
        }
    }
}

但是,这不起作用。当我调用 show() 函数时,它只会保持相同的颜色。有谁知道为什么这不起作用?

如果您想知道我为什么使用循环,那是因为没有数组就不能 getElementsByClassName,因为元素与数组一起使用。

需要使用“===”的比较运算符,而不是“=”的赋值运算符。这也有点令人困惑,因为看起来您希望 topcon 是一个项目数组,在这种情况下,您还需要更改与所选元素的比较。

var topcon = document.getElementsByClassName("topchoice");

function show() {
  var changeColor = "blue";
  if(topcon && topcon.length) {
    if(topcon[0].style.color === "blue") {
      changeColor = "green";
    } else {
      changeColor = "blue";
    }
    for (count=0; count < topcon.length; count++) {
       topcon[count].style.color = changeColor;
    }
  }
};

代码中有 2 个问题

  • 需要使用比较运算符=====进行比较
  • topcon是一个节点列表,所以它没有style属性。这将导致您的代码抛出类似 Uncaught TypeError: Cannot set property 'color' of undefined
  • 的错误

var topcon = document.getElementsByClassName("topchoice");

function show() {
  var el;
  for (count = 0; count < topcon.length; count++) {
    el = topcon[count];
    if (el.style.color == "blue") {
      el.style.color = "green";
    } else if (el.style.color == "green") {
      el.style.color = "blue";
    }
  }
}
<div class="topchoice" style="color: green">1</div>
<div class="topchoice" style="color: green">1</div>
<div class="topchoice" style="color: green">1</div>
<div class="topchoice" style="color: green">1</div>

<button onclick="show()">Show</button>