简体   繁体   English

如何使用 javascript 获取 css 变量名(键)

[英]How can I get css variable name(key) with javascript

I'm working on a project and I designed a custom ripple, but I need to name of the css variable I wanted apply the ripple on, something like this我正在做一个项目,我设计了一个自定义波纹,但我需要命名我想应用波纹的 css 变量,像这样

 function setRipple(){ // I want my ripple to be like this var elementColor = // The button background-color variable name; var ripple color = `var(--${elementColor}-tint)` // Other things goes here }
 :root{ --color-primary: #00cc67; --color-primary-shade: #008040; --color-primary-tint: #e5fff2; }.btn{ background-color:var(--color-primary) }
 <html> <body> <button class="btn">Ripple button</button> </body> </html>

This is fragile, but it sets the ripple value by appending -tint to the element color as you specified.这很脆弱,但它通过将-tint附加到您指定的元素颜色来设置波纹值。

The function looks into the first (and only the first) stylesheet in the document, finds the :root rule, and inspects the list of CSS " --color- " variable keys found there. function 查看文档中的第一个(也是唯一一个)样式表,找到:root规则,并检查在其中找到的--color- “--color-”变量键的列表。 When it finds one whose value matches the button's color, it uses that key to make the rippleColor string.当它找到一个值与按钮颜色匹配的值时,它使用该键来生成rippleColor字符串。

The fragility comes mostly from the way color matching is done (and there must be a better way to do this.) Also, if there were, for some reason, several variable keys with the same matching value, the last match would be selected.脆弱性主要来自颜色匹配的完成方式(并且必须有更好的方法来做到这一点。)此外,如果由于某种原因有几个具有相同匹配值的变量键,则将选择最后一个匹配项。

Thanks for the puzzle.谢谢你的谜题。 Stylesheet manipulation is a fascinating beast.样式表操作是一头迷人的野兽。

 let rippleColor = setRipple(); console.log(`ripple color will be: ${rippleColor}`) function setRipple() { let elementColorName = ""; const btn = document.querySelector(".btn"), btnColorVal = getComputedStyle(btn).getPropertyValue("background-color").toString(), firstSheet = document.styleSheets[0], rules = Array.from(firstSheet.cssRules); rules.filter(r => r.type === 1 && r.selectorText === ":root").map(rule => { Object.entries(rule.style).filter(entry => parseInt(entry[0]) > -1).forEach(entry => { const varName = entry[1], varVal = getComputedStyle(document.documentElement).getPropertyValue(varName).trim(), match = hexToRgb(varVal) === btnColorVal; if(match){ elementColorName = varName; } }); }); console.log("the button's color is: " + elementColorName); const rippleColor = `var(${elementColorName}-tint)`; return rippleColor; } function hexToRgb(hex){ const c = '0x' + hex.slice(1); return 'rgb(' + [ (c >> 16) & 255, (c >> 8) & 255, c & 255 ].join(', ') + ')'; }
 :root { --color-primary: #00cc67; --color-primary-shade: #008040; --color-primary-tint: #e5fff2; }.btn { background-color: var(--color-primary) }
 <html> <body> <button class="btn">Ripple button</button> </body> </html>

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

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