使用JavaScript获取和设置CSS变量

Getting and Setting CSS Variables using JavaScript?

本文关键字:CSS 变量 设置 JavaScript 获取 使用      更新时间:2023-09-26

这周我发现了CSS3变量的荣耀!爱他们!

:root {
    --main-height: 45px;
    --main-gutter: -8px;
    --match-width: 180px;
    --player-width: 370px;
    --score-width: 60px;
}

我的问题…有一种方法,我可以获得/设置这些变量在JavaScript?

这里有一个工作的演示CODEPEN和下面的代码片段。详细信息在源代码中有注释。

关键部分是:

setProperty和模板字面值

// Collect the inputs
const adjGrp = [].slice.call(document.querySelectorAll('#adjustments input'));
// Add an eventListener to each input for the change event
adjGrp.forEach(input => input.addEventListener('change', adjCSS));
// Event handler uses setProperty method and template literal of the CSS variable 
// Input name attributes are referenced to the corresponding CSS variable
function adjCSS(e) {
  document.documentElement.style.setProperty(`--${this.name}`, this.value + 'px');
}
:root {
  --mainh: 45px;
  --mainw: 480px;
  --match: 180px;
  --player: 370px;
  --score: 60px;
}
#main {
  font: 500 16px/1.5 Consolas;
  height: var(--mainh);
  width: var(--mainw);
}
#scoreboard {
  display: table;
  width: calc(var(--player) + 150px);
  height: calc((var(--main) * .2));
  margin: 15px 0 15px 20px;
}
legend {
  font-size: 1.6rem;
  font-variant: small-caps;
}
output {
  display: table-cell;
  line-height: 1.5;
  border: 3px inset grey;
  padding: 3px 5px;
}
#match {
  width: var(--match);
}
#player {
  width: var(--player);
}
#score {
  width: var(--score);
}
#adjustments {
  margin: 0 0 0 20px;
}
<form id='main'>
  <fieldset id='scoreboard'>
    <legend>Scoreboard</legend>
    <input id='m' type='hidden'>
    <input id='p' type='hidden'>
    <input id='s' type='hidden'>
    <label>Player
      <output id='player' for='p'>Name</output>
      <br/>
    </label>
    <label>Match&nbsp;
      <output id='match' for='m'>0</output>
      <br/>
    </label>
    <label>Score&nbsp;
      <output id='score' for='s'>0</output>
    </label>
  </fieldset>
  <fieldset id='adjustments'>
    <legend>Adjustments</legend>
    <label>Player
      <input name='player' type='number'>
    </label>
    <br/>
    <label>Match&nbsp;
      <input name='match' type='number'>
    </label>
    <br/>
    <label>Score&nbsp;
      <input name='score' type='number'>
    </label>
    <br/>
  </fieldset>
</form>

你可以创建一个样式元素,并将其附加到包含任何CSS的<head>

$("head").append(`
   <style type="text/css">
    CSS CODE
   </style>
`);

虽然你可能不应该使用CSS变量如果你关心跨浏览器的兼容性。