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

标签 javascript colors getelementsbyclassname

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

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,因为元素与数组一起使用。

最佳答案

代码中有 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>

关于javascript - 使用 "If statement"获取 Javascript 中彩色文本的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40901613/

相关文章:

javascript - 无法为 particles.js div 设置动画

javascript - 日期验证 : validating Return date is after departure date using datepicker( )

node.js - 颜色.js : Proper syntax for adding a color to a variable (string)?

javascript - 样式背景图像与 JS 不工作

javascript - querySelectorAll和getElementsBy *方法返回什么?

javascript - 如何在 setAttribute java 脚本函数中动态添加输入类型范围缩略图 css

r - 向箱线图添加颜色 - "Continuous value supplied to discrete scale"错误

node.js - 使用 NPM 运行脚本在终端中进行彩色登录

javascript - * 选择器适用于 getElementsByTagName(),但不适用于 javascript 中的 getElementsByClassName()?

javascript - 阻止用户通过按 Enter 键提交表单