[英]Displaying value of a CSS Variable in Frontend
I am trying to setup a general Style Guide for my design system.我正在尝试为我的设计系统设置通用样式指南。 I am using CSS Variables for the defined colors like
我正在为定义的 colors 使用 CSS 变量,例如
:root { --accent: #234a32; --accent-alt:#826284 }
I want to display a square in the frontend where I would use the variable as background color but also display the hexvalue in it in order to be able to copy it.我想在前端显示一个正方形,我将在其中使用变量作为背景颜色,但还要在其中显示十六进制值以便能够复制它。
<div style="background-color: var(--accent)">#234a32</div>
So the question is, how can I get the hexcode (in this case #234a32) dynamically to be displayed.所以问题是,我怎样才能动态显示十六进制代码(在本例中为#234a32)。
So first off, your root is wrong.所以首先,你的根是错误的。
:root { --accent: #234a32; --accent-alt:#826284 }
Second you will need to use data-attributes.其次,您将需要使用数据属性。 (unless you wanna do some janky regex to find the var values)
(除非你想做一些 janky regex 来查找 var 值)
<div
style="background-color: var(--accent)"
class="js-populate-var"
data-var="--accent">
<p>placeholder</p>
</div>
var els = document.querySelectorAll('.js-populate-var');
els.forEach(el => {
el.innerHTML = getComputedStyle(el)
.getPropertyValue(el.dataset.var);
})
https://codepen.io/michaelmano/pen/poRqPVj https://codepen.io/michaelmano/pen/poRqPVj
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.