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

如何在未知CSS变量名时用JavaScript获取HTML元素的所有CSS变量?

获取HTML元素所有CSS变量的跨浏览器方案

单个CSS变量的获取方法

如果已知CSS变量名(比如--thing),可以通过以下代码在Chrome和Firefox中获取其值:

const elem = document.querySelector("html");
if (!elem) return;
const style = getComputedStyle(elem);
const myVariable = style.getPropertyValue("--thing");
console.log({ myVariable });

遍历获取所有CSS变量的问题

尝试直接遍历getComputedStyle返回的样式对象、筛选以--开头的属性名的方法,在Firefox中可行,但在Chrome中无效——因为Chrome的style.length不会包含自定义CSS变量。

跨浏览器解决方案

以下代码可以同时兼容Chrome和Firefox(通过特性检测区分实现逻辑):

const res: Record<string, string> = {};

if ("computedStyleMap" in elem) {
  // Chrome 环境逻辑
  const styles = elem.computedStyleMap();
  Array.from(styles).forEach(([prop, val]) => {
    if (prop.startsWith("--")) {
      res[prop] = val.toString();
    }
  });
} else {
  // Firefox 环境逻辑
  const styles = getComputedStyle(elem);
  for (let i = 0; i < styles.length; i++) {
    const propertyName = styles[i];
    if (propertyName.startsWith("--")) {
      const value = styles.getPropertyValue(propertyName);
      res[propertyName] = value;
    }
  }
}

console.log({ res });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 10:02:48