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

新手上路,请多包涵

如何使用 JavaScript(纯文本或 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>

原文由 MarcZ 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 336
2 个回答

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

原文由 CMedina 发布,翻译遵循 CC BY-SA 4.0 许可协议

本机解决方案

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

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

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

但是,如果已使用 .setProperty() 设置,getter 将仅返回 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() 方法。然后吸气剂将如下所示:

 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

原文由 colxi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题