相关疑难解决方法(0)

通过JavaScript访问CSS自定义属性(也称为CSS变量)

如何var(…)使用JavaScript(plain或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>
Run Code Online (Sandbox Code Playgroud)

javascript css jquery css-variables

31
推荐指数
3
解决办法
1万
查看次数

标签 统计

css ×1

css-variables ×1

javascript ×1

jquery ×1