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

标签 javascript jquery css css-variables

如何使用 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>

最佳答案

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

关于javascript - 通过 JavaScript 访问 CSS 自定义属性(又名 CSS 变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52181744/

相关文章:

html - IE8 中的 CSS 最大宽度

html - Style div display table-row 是否可以设置样式

JavaScript FocusEvent relatedTarget 属性在 firefox 中不起作用

javascript - 使用 Raphaël.js 对旋转对象进行动画处理

javascript - 将 DIV 拖动到水平可排序容器

javascript - ajax调用后在php脚本中使用echo时语法错误,无法识别jquery表达式

jquery - 使用 jquery post 发送文件,无需页面刷新 mvc

html - 断点没有按预期工作

javascript - 尝试从 Sublime Text 运行 JS 时出现 WinError 5

javascript - 当 3 个表单区域需要具有值时,通过 jQuery 处理按钮启用