如何获取元素style中原始hsl/hwb颜色值?浏览器是否将调整此机制?
问题背景
暗橄榄绿色文本是元素style属性中设置的原始color值,黑色文本是通过element.style.color获取到的浏览器标准化后的值。MDN指出rgba逗号分隔的写法已过时(仍受支持),但Chrome、Firefox和Safari中,element.style.color返回的仍是rgba逗号形式,同时element.style会把hsl()、hwb()转换为rgba(),style.cssText也会转为rgb格式。
核心问题
- 有没有办法获取CSS/HTML中
style设置的原始值,保留hsl和hwb的原函数及参数?至少能知道用户指定的函数类型也好。 - 这种转换是永久状态吗?浏览器或规范是否有更改计划?
代码示例
HTML
<p style="color:rgb(85.1 107 46.9 / 0.9)">rgb(85.1 107 46.9 / 0.9)</p> <p id="rgb"></p> <br> <p style="color:hsl(82 39% 30.2% / 0.9)">hsl(82 39% 30.2% / 0.9)</p> <p id="hsl"></p> <br> <p style="color:hwb(82 18.4% 58% / 0.9)">hwb(82 18.4% 58% / 0.9)</p> <p id="hwb"></p> <br> <p style="color:lab(42.23 -18.83 30.6 / 0.9)">lab(42.23 -18.83 30.6 / 0.9)</p> <br> <p style="color:color(srgb 0.3453 0.4269 0.1943 / 0.9)">color(srgb 0.3453 0.4269 0.1943 / 0.9)</p> <p id="col"></p> <br> <p id="lab"></p> <p id="computed"></p> <p id="cssText"></p>
CSS
p { font-family:monospace; font-size:1.1em; margin:0; }
JavaScript
const rgb = document.getElementById("rgb"); const hsl = document.getElementById("hsl"); const hwb = document.getElementById("hwb"); const lab = document.getElementById("lab"); const col = document.getElementById("col"); rgb.textContent = rgb.previousElementSibling.style.color; hsl.textContent = hsl.previousElementSibling.style.color; hwb.textContent = hwb.previousElementSibling.style.color; lab.textContent = lab.previousElementSibling.style.color; col.textContent = col.previousElementSibling.style.color; document.getElementById("computed").textContent = "hwb computed> " + getComputedStyle(hwb.previousElementSibling).color; document.getElementById("cssText").textContent = "hwb cssText > " + hsl.previousElementSibling.style.cssText;
解答
1. 获取原始style值的方法
直接通过element.style或getComputedStyle无法拿到原始格式——浏览器会将CSS值解析后标准化存储。但可以通过以下方式获取:
- 内联样式场景:读取元素的
style属性原始字符串,自行解析。比如用element.getAttribute('style')拿到完整的内联样式文本,再通过字符串匹配提取color属性的原始值。示例代码:function getOriginalColor(el) { const styleStr = el.getAttribute('style'); if (!styleStr) return null; const colorMatch = styleStr.match(/color:\s*([^;]+)/i); return colorMatch ? colorMatch[1].trim() : null; } // 使用示例 const hslEl = document.querySelector('[style*="hsl"]'); console.log(getOriginalColor(hslEl)); // 输出原始hsl格式 - 外部/内部样式表场景:需要遍历
document.styleSheets中的样式规则,找到对应元素的样式声明。这种方法较复杂,且存在跨域限制(无法读取跨域样式表)。
2. 浏览器行为的未来趋势
目前浏览器的标准化转换行为符合CSS规范,规范并未要求浏览器保留CSS属性的原始书写格式,而是允许将其转换为统一的内部表示后返回。
短期内没有迹象表明主流浏览器会更改这一行为——标准化后的格式更便于JavaScript统一处理颜色值。不过随着CSS Color Module Level 4的普及,未来可能会对lab、color()这类新颜色函数的返回格式进行调整,但核心的标准化逻辑大概率会保持不变。
内容的提问来源于stack exchange,提问作者Sideways S
相关产品推荐
相关产品推荐

