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

IT技术 javascript jquery css css-variables
2021-01-20 03:24:42

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

这是我失败的尝试:单击按钮会更改通常的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>
3个回答

您可以使用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

更多信息在这里

它可以用作全局变量,无需加载新文件 CSS 即可更改
2021-03-13 03:24:42
对于想要在<html>-tag 而不是正文上获取或设置属性的任何人:您可以使用document.documentElement.
2021-03-30 03:24:42
该集合是否还将 CSS 中对该变量的所有引用更新为?
2021-04-02 03:24:42
影子根里面的样式怎么样?
2021-04-11 03:24:42

原生解决方案

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

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

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

但是,如果已设置,getter 将仅返回 var 的值,使用.setProperty(). 如果已通过 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>

为了避免这种意外行为,您必须getComputedStyle()在调用之前使用该方法.getPropertyValue()然后 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

@Dave.QI 那种情况下你可以使用 Sass 或 Less,否则我不知道如何直接公开这些值
2021-03-14 03:24:42
我知道这是一个较旧的问题,但是您将如何将样式表中的实际 var(--varName) 动态更改为所选值?如果我想为用户提供样式表,我希望用户看到实际的颜色名称或十六进制值,而不是 var(--varName)。例如,参见stackoverflow.com/q/59507329/10964617
2021-03-22 03:24:42
@connexo 完全正确。undefined按预期输出再次阅读代码片段之前的注释。
2021-03-22 03:24:42
当您需要在 JS 中操作变量时,我喜欢它,但在我的情况下,我只需要获取值。因此,我只需要一个帮助函数返回,而不是一个完整的帮助程序库getComputedStyle(document.documentElement,null).getPropertyValue(varStr);
2021-04-05 03:24:42

以下示例说明了如何使用 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设置为新值。