十六进制不起作用

时间:2013-09-12 12:37:04

标签: javascript html css colors

这是怎么回事 (div cirlcedecider2的风格为“绿色”)

function badge1(){
if (document.getElementById("circledecider2").style.color == "green"){

document.getElementById("badge1").style.backgroundColor= "#ABCF37";
document.getElementById("badge1").style.width = "200px";
document.getElementById("badge1").style.height = "200px";

}}

但这不是吗? (div cirlcedecider2的样式为“#ABCF37”)

function badge1(){
if (document.getElementById("circledecider2").style.color == "#ABCF37"){

document.getElementById("badge1").style.backgroundColor= "#ABCF37";
document.getElementById("badge1").style.width = "200px";
document.getElementById("badge1").style.height = "200px";

}}

唯一的区别是使用十六进制代码。

3 个答案:

答案 0 :(得分:0)

解析

#ABCF37 并将其更改为其他格式。结果很可能是浏览器特定的。

document.body.style.color = "#ABCF37"
document.body.style.color; // "rgb(171, 207, 55)"

显然

"rgb(171, 207, 55)" == "#ABCF37"; // false

您需要编写一些函数来解释颜色并返回可以比较的标准(可能是rgba格式),或者比较两种颜色的函数(这可能更容易)。

function compareColour(col1, col2) {
    var e = document.createElement('span')
    document.body.appendChild(e);
    // standardise
    e.style.color = col1;
    col1 = window.getComputedStyle(e).color;
    e.style.color = col2;
    col2 = window.getComputedStyle(e).color;
    // cleanup
    document.body.removeChild(e);
    return col1 === col2;
}

compareColour("#ABCF37", "rgb(171, 207, 55)"); // true

答案 1 :(得分:0)

Reference color

function badge1(){
if (document.getElementById("circledecider2").style.color == "rgb(171, 207, 55)")
{

document.getElementById("badge1").style.backgroundColor= "#ABCF37";
document.getElementById("badge1").style.width = "200px";
document.getElementById("badge1").style.height = "200px";

}}

答案 2 :(得分:0)

您检索的颜色为浏览器特定

IE中,您可以看到浏览器返回hex值,因此您的代码也应该比较小hex值中的字母,例如#abcf37

chrome等其他浏览器会以rgb格式返回。

替代解决方案是在rgb中返回以十六进制格式转换值。

请参阅答案here了解备用解决方案。