JavaScript ermöglicht den Zugriff auf benutzerdefinierte CSS-Eigenschaften (auch als CSS-Variablen bezeichnet).
P粉420868294
P粉420868294 2023-10-20 22:42:04
0
2
593

Wie kann ich benutzerdefinierte CSS-Eigenschaften (Eigenschaften, auf die über var(…) in einem Stylesheet zugegriffen wird) mithilfe von JavaScript (einfach oder jQuery) abrufen und festlegen?

Das ist mein erfolgloser Versuch: Durch Klicken auf die Schaltfläche werden die üblichen font-weight 属性,但不会更改自定义 --mycolor Eigenschaften geändert:

<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>

P粉420868294
P粉420868294

Antworte allen(2)
P粉421119778

原生解决方案

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

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

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

但是,如果已使用 .setProperty() 设置了 var 的值,则 getter 只会返回该值。 如果已通过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() 之前使用 getCompulatedStyle() 方法。 然后吸气剂将如下所示:

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

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


我个人的做法

我实现了 CSSGlobalVariables 一个小型 (以便更轻松地访问和操作.

// 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-全局变量

P粉863295057

您可以使用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
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!