3

I'm using :root to create some CSS variables. Is it possible to create them with JavaScript instead of CSS? Below is a simple example:

<div id="container"></div>
:root {
  --first-color: #000;
  --second-color: #666666;
}

#container {
  background-color: var(--second-color);
  width: 90px;
  height: 90px;
}
4

1 回答 1

4

是的,你可以通过.setProperty()方法做到这一点:

const root = document.documentElement;
root.style.setProperty('--first-color', 'red');
root.style.setProperty('--second-color', 'blue');
p {
  color: var(--first-color);
}

div {
  color: var(--second-color);
}
<p>First color</p>
<div>Second color</div>

于 2021-12-23T19:34:16.400 回答