简体   繁体   English

获取 css prop 的变量名

[英]Get variable name of css prop

I'm trying to get the name of the variable used in CSS on an element我正在尝试获取元素上 CSS 中使用的变量的名称

How can I return the string --my-background from document.getElementById("my_div")如何从document.getElementById("my_div")返回字符串--my-background

getComputedStyle returns #000 getComputedStyle返回#000

 :root { --my-background: #000; }.my_class { background-color: var(--my-background); }
 <div id="my_div" class="my_class"> Test </div>

I can't use the solution shown at How can I get css variable name(key) with javascript because multiple variables will have the same hex code我无法使用How can I get css variable name(key) with javascript中显示的解决方案,因为多个变量将具有相同的十六进制代码

Not 100% sure what you are after actually不能 100% 确定您实际上在追求什么

THIS is a closely related question: Can I detect if a specific CSS custom variable exists in the loaded styles?这是一个密切相关的问题:我可以检测加载的 styles 中是否存在特定的 CSS 自定义变量吗?

Here as a verbose example of two different possible ways to get to what you are after;这是一个详细的例子,说明了两种不同的可能方式来达到你所追求的目标; one on the entire document and one JUST on your element.一个在整个文件上,一个在你的元素上。

LOTS of comments and commented out parts here.这里有很多评论和注释掉的部分。

 const declaration = document.styleSheets[0].cssRules[0].style; //console.log(declaration);//huge list const decValues = Object.values(declaration); // just values //console.log("decValues:",decValues); // just the ONE value we "know" starts with //const foundVars = decValues.filter((v) => { return v.startsWith("--");}); //console.log("foundVars:",foundVars);// shows value for those (one) with it let declarationC = Object.getOwnPropertyNames(declaration); // console.log("declarationC:",declarationC); // just the property names // the properties that start with "--" const allNotEmptyComputedStyles = Object.fromEntries( Object.entries(declaration).filter( ([_, value]) => value.startsWith("--") ) ); // this is "0" key name because that is where it IS in the properties console.log("allNotEmptyComputedStyles:", allNotEmptyComputedStyles); /* now a different way just on the element */ let me = document.getElementById("my_div"); let cs = getComputedStyle(me); // big list of all console.log("cs:",cs); let cspv = cs.getPropertyValue('--my-background'); console.log("cspv:", cspv); console.log("PV:", allNotEmptyComputedStyles["0"], cs.getPropertyValue(allNotEmptyComputedStyles["0"]));
 :root { --my-background: #000; }.my_class { background-color: var(--my-background); }
 <div id="my_div" class="my_class"> Test </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM