在firefox中使用element.style.color

Using element.style.color within firefox

本文关键字:element style color firefox      更新时间:2023-09-26

我有下面的JavaScript函数,它可以更改元素中的文本,作为一种家务劳动,我还希望确保文本可读。因此,我为深色背景设置了白色,否则设置为黑色。

现在,该代码在IE9和Chrome上可以正常工作,但由于某些原因,无法正确更改Firefox上的颜色属性。为什么会这样?Firefox是否不支持我访问颜色属性的方式?

function setTextContent(element, text) {
    while (element.firstChild!==null)
        element.removeChild(element.firstChild); // remove all existing content
    element.appendChild(document.createTextNode(text));
    if (element.style.backgroundColor == "black"
          || element.style.backgroundColor == "purple"
          || element.style.backgroundColor == "blue") {
      element.style.color = "white";
    } else {
      element.style.color = "black";
    }
}

为什么不使用类?

.blackBackground {
    background-color: black;
    color: white;
}
.purpleBackground {
    background-color: purple;
    color: white;
}

等等

啊,所以最后的问题是区分大小写。

"黑色"不等于"黑色"。应该意识到这一点:)

想想,element.firstChild会变成null吗?它会被设置为一个空的文本节点或类似的东西吗?

当条件类似时进行检查

 while (element.firstChild!==null)//wrong

它应该像

   while (element.firstChild!=null)

或简称

while (element.firstChild)