【问题标题】:Get CSS variables applied to an element获取应用于元素的 CSS 变量
【发布时间】:2021-06-08 15:16:49
【问题描述】:

在 chrome / chromium 中,我想列出应用于 HTML 元素的所有 CSS 变量(变量名称和值)。以下代码在 Firefox 中有效,但在 webkit 浏览器中不支持接缝。有没有可能的解决方法?

let style = getComputedStyle(document.body);
for (let i = 0; i < style.length; i++) {
  let prop = style[i]
  if(prop.includes("--")){
    let val = style.getPropertyValue(prop)
    document.body.innerHTML = "Works in Firefox but not in Chromium:<br>"
    document.body.innerHTML += prop+" "+val
  }
}
:root{
  --c:lime;
}
body{
  background:var(--c);
}

【问题讨论】:

  • style.getPropertyValue('--c') // lime 适用于 Chrome 和 Firefox。
  • @evolutionxbox 指导性的,谢谢!是的,getPropertyValue 有效,但就我而言,我不知道变量的名称,我需要检索它。
  • @evolutionxbox 这确实解决了我的问题!谢谢你。我会回复我的帖子。

标签: javascript webkit css-variables


【解决方案1】:

这样就解决了问题:

const isSameDomain = (styleSheet) => {
  if (!styleSheet.href) {
    return true;
  }

  return styleSheet.href.indexOf(window.location.origin) === 0;
};

const isStyleRule = (rule) => rule.type === 1;

const getCSSCustomPropIndex = () =>
  [...document.styleSheets].filter(isSameDomain).reduce(
    (finalArr, sheet) =>
      finalArr.concat(
        [...sheet.cssRules].filter(isStyleRule).reduce((propValArr, rule) => {
          const props = [...rule.style]
            .map((propName) => [
              propName.trim(),
              rule.style.getPropertyValue(propName).trim()
            ])
            .filter(([propName]) => propName.indexOf("--") === 0);

          return [...propValArr, ...props];
        }, [])
      ),
    []
  );

document.body.innerHTML = getCSSCustomPropIndex()
html {
  --c: lime;
}

 body {
  background:var(--c);
}

感谢@evolutionxbox 指点solution

【讨论】:

    猜你喜欢
    • 2012-12-08
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    相关资源
    最近更新 更多