通过 JavaScript 访问 CSS 自定义属性(又名 CSS 变量)

Accessing a CSS custom property (aka CSS variable) through JavaScript

本文关键字:CSS 又名 变量 自定义属性 JavaScript 访问 通过      更新时间:2023-09-26

如何使用JavaScript(plain或jQuery)获取和设置CSS自定义属性(在样式表中使用var(…)访问的属性)?

这是我不成功的尝试:单击按钮会更改通常的font-weight属性,但不会更改自定义--mycolor属性:

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <style>
    body { 
      --mycolor: yellow;
      background-color: var(--mycolor);
    }
  </style>
</head>
<body>
  <p>Let's try to make this text bold and the background red.</p>
  <button onclick="plain_js()">Plain JS</button>
  <button onclick="jQuery_()">jQuery</button>
  <script>
  function plain_js() { 
    document.body.style['font-weight'] = 'bold';
    document.body.style['--mycolor'] = 'red';
  };
  function jQuery_() {
    $('body').css('font-weight', 'bold');
    $('body').css('--mycolor', 'red');
  }
  </script>
</body>
</html>
您可以使用

document.body.style.setProperty('--name', value);

var bodyStyles = window.getComputedStyle(document.body);
var fooBar = bodyStyles.getPropertyValue('--foo-bar'); //get
document.body.style.setProperty('--foo-bar', newValue);//set

原生解决方案

获取/设置 CSS3 变量的标准方法是.setProperty().getPropertyValue()

如果您的变量是全局变量(在 :root 中声明),则可以使用以下方法来获取和设置它们的值。

// setter
document.documentElement.style.setProperty('--myVariable', 'blue');
// getter
document.documentElement.style.getPropertyValue('--myVariable');

但是,getter 只会使用 .setProperty() 返回 var 的值(如果已设置)。 如果已经通过CSS声明设置,将返回undefined。 在此示例中检查它:

let c = document.documentElement.style.getPropertyValue('--myVariable');
alert('The value of --myVariable is : ' + (c?c:'undefined'));
:root{ --myVariable : red; }
div{ background-color: var(--myVariable); }
  <div>Red background set by --myVariable</div>

为了避免这种意外行为,您必须在调用.getPropertyValue()之前使用 getComputedStyle() 方法。然后,getter 将如下所示:

getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');

在我看来,访问 CSS 变量应该更简单、更快速、更直观、更自然......


我的个人方法

我已经实现了CSSGlobalVariables一个小(<3kb)javascript助手,它会自动检测文档中的所有活动CSS全局变量并将其打包到一个对象中,以便于访问和操作

// get the document CSS global vars
let cssVar = new CSSGlobalVariables();
// set a new value to --myVariable
cssVar.myVariable = 'red';
// get the value of --myVariable
console.log( cssVar.myVariable );

应用于对象属性的任何更改都会自动转换为 CSS 变量。

可用语言 : https://github.com/colxi/css-global-variables

下面的示例说明了如何使用JavaScript或jQuery更改背景,利用也称为CSS变量的自定义CSS属性(在此处阅读更多内容)。奖励:该代码还指示如何使用CSS变量来更改字体颜色。

function plain_js() { 
    // need DOM to set --mycolor to a different color 
    d.body.style.setProperty('--mycolor', 'red');
     
    // get the CSS variable ...
    bodyStyles = window.getComputedStyle(document.body);
    fontcolor = bodyStyles.getPropertyValue('--font-color'); //get
 
    // ... reset body element to custom property's new value
    d.body.style.color = fontcolor;
    d.g("para").style["font-weight"] = "bold";
    this.style.display="none";
  };
  function jQuery_() {
    $("body").get(0).style.setProperty('--mycolor','#f3f');
    $("body").css("color",fontcolor);
    $("#para").css("fontWeight","bold");
    $(this).css("display","none");
  }
  
var bodyStyles = null;
var fontcolor = "";
var d = document;
d.g = d.getElementById;
d.g("red").addEventListener("click",plain_js);
d.g("pink").addEventListener("click",jQuery_);
:root {
     --font-color:white;
     --mycolor:yellow;
    }
    body { 
      background-color: var(--mycolor);
      color:#090;
    }
    
    #para {
     font: 90% Arial,Helvetica;
     font-weight:normal;
    }
    
    #red {
      background:red;
    }
    
    #pink {
      background:#f3f;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<p id="para">Let's try to make the background red or pink and change the text to white and bold.</p>
  <button id="red">Red</button>
  <button id="pink">Pink</button>

请注意,对于 jQuery,为了将自定义属性设置为不同的值,此响应实际上包含答案。 它使用 body 元素的 get() 方法,该方法允许访问底层 DOM 结构并返回 body 元素,从而便于将自定义属性--mycolor设置为新值的代码。

可以使用

getComputedStyle函数来获取css变量,下面是一个示例。

const colors = document.querySelectorAll(".color");
const result = document.getElementById("result");
colors.forEach((color) => color.addEventListener("click", changeColor));
function changeColor(event) {
  const target = event.target;
  // get color
  const color = getComputedStyle(target).getPropertyValue("--clr");
  document.body.style.backgroundColor = color;
  // active color
  colors.forEach((color) => color.classList.remove("active"));
  target.classList.add("active");
  
  result.textContent = getComputedStyle(target).getPropertyValue("--clr")
  
}
result.textContent = "#1dd1a1";
body{
  background-color: #1dd1a1;
}
.colors{
  position: absolute;
  padding: 2rem;
  display: flex;
  gap: 1rem;
}
.color{
  display: inline-block;
  width: 2rem;
  height: 2rem;
  background-color: var(--clr);
  border-radius: 50%;
  cursor: pointer;
  transition: $time-unit;
  }
  .color.active{
    border: .2rem solid #333;
    transform: scale(1.25);
  }
<h1>Click to change Background</h1>
<section class="colors">
  <span class="color active" style="--clr: #1dd1a1"></span>
  <span class="color" style="--clr: #ff6b6b"></span>
  <span class="color" style="--clr: #2e86de"></span>
  <span class="color" style="--clr: #f368e0"></span>
  <span class="color" style="--clr: #ff9f43"></span>
</section>
Current Color: <span id="result"></span>