我正在解析返回的颜色字符串getComputedStyle
to get R
, G
, B
, and A
从中获取价值。
到目前为止(在 Chrome 和 Firefox 中),颜色值似乎总是返回rgb
or rgba
易于解析的格式:
const [, r, g, b, a] = str.replace(/\s/g, "").match(/rgba?\((\d+(?:\.\d+)?),(\d+(?:\.\d+)?),(\d+(?:\.\d+)?)(?:,(\d+(?:\.\d+)?))?\)/i);
但是,我无法找到有关颜色格式的任何承诺any https://www.w3.org/TR/DOM-Level-2-Style/#CSS-CSSview-getComputedStyle of the specs https://drafts.csswg.org/cssom/#dom-window-getcomputedstyle for getComputedStyle
列于其MDN page https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle.
是否有任何颜色格式的保证getComputedStyle
?还是完全取决于浏览器的实现?
我不想检查 HEX 和 HSLA 值(实际上还有其他可能的值 - 我不完全确定)。
用于在控制台中测试颜色值的快速代码片段:
console.log((str => {
const div = document.createElement("div");
div.style.backgroundColor = str;
document.body.append(div);
return getComputedStyle(div).backgroundColor;
})("magenta"));