【问题标题】:Is there a reason why Javascript's "document.querySelector().style.backgroundColor" converts HEX to RGB?Javascript 的“document.querySelector().style.backgroundColor”将 HEX 转换为 RGB 是否有原因?
【发布时间】:2021-01-18 10:32:25
【问题描述】:

这是我在这里的第一个问题,请温柔。我刚刚注意到在 Safari、Chrome 和 Firefox 的控制台中,以下脚本中的颜色值总是返回 RGB 值而不是 HEX 值。并不是说它阻止了代码工作或任何事情,我只是想知道为什么控制台不返回发送的 HEX 值? Javascript 是否总是将颜色值转换为 RGB?它是不是其他范式的一等公民?

function randomHEX() {
    var HEXvalues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];
    var newHEX = "#";

    for (i = 0; i < 6; i++) {
        var nextIndex = Math.floor(Math.random() * HEXvalues.length); // grab a random value from the array
        newHEX += HEXvalues[nextIndex]; // increment values to newHEX
    }

    document.querySelector("#hexName").textContent = newHEX; // use newHEX to fill text of ID hexName
    document.querySelector(".container").style.backgroundColor = newHEX; // use newHEX to change background color of box
}

Safari console window

任何信息将不胜感激。

非常感谢。


PS

感谢回复的人。我的问题是为什么 RGB? 为什么不默认接收到的十六进制数? 为什么 Javascript 使用 .style.backgroundColor 将 HEX 值转换为 RGB 值?

再次,非常感谢。

【问题讨论】:

    标签: javascript html methods hex rgb


    【解决方案1】:

    是的,默认情况下它显示为 RGB。要将其转换为 HEX,这里已经回答了 link

    【讨论】:

      【解决方案2】:

      这不是你的问题。您的函数使 HEX 值正确。您可以通过在函数末尾添加console.log(newHEX) 来检查它。

      element.style.color = HEX_string会转成RGB值。

      如果您需要将其转换回来,请查看this question

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-25
        • 2013-04-03
        • 2016-08-11
        • 2013-03-28
        • 2018-01-31
        • 2015-07-04
        • 2019-02-08
        • 2017-07-26
        相关资源
        最近更新 更多