如何获取计算出的CSS颜色字符串的值?

时间:2018-05-11 16:09:57

标签: javascript css dom domdocument computed-properties

我需要获取CSS颜色的颜色值(任何格式,十六进制,rgb等)"名称"或字符串。例如"blue",我希望返回"#0000ff""rgb(0, 0, 255)"

我需要的特定颜色是-moz-win-accentcolor,在Firefox上可用,以获得Windows 10个性化设置中的强调颜色设置。

我尝试使用CSS中的计算样式使用以下代码,并生成"rgb(57, 66, 69)"。我个性化设置的颜色就是这样。

这是该功能的代码:

const testInput0 = document.getElementById("test-input-0");
const testInput1 = document.getElementById("test-input-1");


function getWindowsAccentColor() {
    let coloredElement = document.createElement("span");
    coloredElement.style.backgroundColor = "-moz-win-accentcolor";
    let colorValue = getComputedStyle(coloredElement).getPropertyValue("background-color");
    coloredElement.remove();

    return colorValue;
}


testInput1.addEventListener("click", () => {
    let colorValue = getWindowsAccentColor();
    testInput0.value = colorValue;
    console.log(colorValue);
});

当我在我的主题Native Dark中使用此CSS颜色时,该值会随着时间的推移而更新(有类似的,有关它的问题中存在错误)。但是,当在JS中使用计算样式时,它会保留旧颜色,直到我完全重新启动浏览器。但它确实改变了。

0 个答案:

没有答案