You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么通过getComputedStyle获取的textDecoration属性会包含rgb值?

问题原因说明
  • window.getComputedStyle 返回的是元素的最终计算样式值,而非你在CSS中写的原始声明值,所以永远不会返回initial、inherit这类关键字,只会返回浏览器实际渲染生效的属性值。
  • text-decoration 是CSS简写属性,完整包含三个子属性:text-decoration-line(线条类型,如underline、none)、text-decoration-color(线条颜色)、text-decoration-style(线条样式如实线、虚线),浏览器返回计算值时会补全所有子属性的默认值,默认线条颜色和元素文本颜色一致,因此会自带rgb颜色值。
    你设置text-decoration: initial时,实际计算值对应的是text-decoration-line: none,加上默认的文本颜色和实线样式,所以返回值会是类似none rgb(0,0,0) solid的格式。
解决方案

方法1(推荐):直接读取独立子属性

不需要处理简写属性的返回值,直接读取textDecorationLine属性即可,返回值就是你需要的纯线条类型值:

const style = window.getComputedStyle(document.getElementById('gettextDecorationfrom'));
// 直接获取线条类型,返回值为 none / underline / line-through 等纯值
const decoLine = style.textDecorationLine;
document.getElementById("results").innerText = decoLine;

该方法兼容性足够,所有现代浏览器和IE11都支持该属性读取。

方法2:正则过滤简写属性返回值

如果必须处理textDecoration简写属性的返回结果,可以用正则匹配移除颜色部分:

const fullDeco = style.textDecoration;
// 过滤所有rgb/rgba颜色片段
const pureDeco = fullDeco.replace(/ ?rgba?\([^)]+\)/g, '');

内容的提问来源于stack exchange,提问作者Glen Keybit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 13:18:03