Javascript 如何找到给定元素的样式中使用的CSS变量?

Javascript 如何找到给定元素的样式中使用的CSS变量?,javascript,css-variables,Javascript,Css Variables,我有一个定义为CSS变量的调色板 :root { --background-normal: #fffff; --text-normal: #212a32; --background-warning: #ff0000; --text-warning: #ffffff; } #article-body { background-color: var(--background-normal); color: var(--text-normal); } 元素的CSS类正在

我有一个定义为CSS变量的调色板

:root {
  --background-normal: #fffff;
  --text-normal: #212a32;
  --background-warning: #ff0000;
  --text-warning: #ffffff;
}
#article-body {
   background-color: var(--background-normal);
   color: var(--text-normal);
}
元素的CSS类正在使用这些变量

:root {
  --background-normal: #fffff;
  --text-normal: #212a32;
  --background-warning: #ff0000;
  --text-warning: #ffffff;
}
#article-body {
   background-color: var(--background-normal);
   color: var(--text-normal);
}
不同的类使用不同的变量。我需要能够做的是分析呈现页面上的某个元素,并告诉它在样式中使用了哪些CSS变量。例如:
div#文章正文
使用变量
background normal
text normal

我可以使用
getComputedStyle
获取元素的计算样式,但是返回的样式将所有CSS变量替换为实际值


关于如何提取包含变量名的CSS有什么想法吗?

到目前为止,我找到的唯一解决方法是更改每个CSS变量,并查看该更改是否出现在任何元素中。大概是这样的:

var bodyStyles = window.getComputedStyle(document.body);
var check = "rgb(12, 34, 56)";
var vars = ["--background-normal", "--text-normal", "--background-warning", "--text-warning"];

function checkUsage (element, index, array) {
  var origValue = bodyStyles.getPropertyValue(element);
  document.body.style.setProperty(element, check);
  var found = false;
  $("#article-body *").each (function(index, el) {
    var allCSS = getComputedStyle(el).cssText;
    if (allCSS.indexOf(check) >= 0) {
        found = true;
    }
    });
  document.body.style.setProperty(element, origValue);
  if (found) console.log(element);
}

vars.forEach(checkUsage);
这工作相当快,你不会注意到闪烁由于颜色的变化。至少在容器内的少量元素上。
如果其中一个CSS变量的原始值与
检查值相同,则此方法有可能出现错误检测。这在我的情况下是可以接受的,但我希望有一种更干净的方法。

为什么要这样做?这是应用程序主题化的一个子任务。我希望用户能够更改页面上不同元素的颜色。在应用程序中有很多带有颜色的CSS变量,我想减少这个数字,只显示在这个特定元素中实际使用的那些。