How do I get and set CSS custom properties (properties accessed via var(…)
in a stylesheet) using JavaScript (plain or jQuery)?
Here is my unsuccessful attempt: clicking the button changes the usual font-weight
properties, but not the custom --mycolor
properties:
<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粉4211197782023-10-21 17:19:53
The standard methods for getting/setting CSS3 variables are .setProperty()
and .getPropertyValue()
.
If your variables are global variables (declared in :root
), you can use the following to get and set their values.
// setter document.documentElement.style.setProperty('--myVariable', 'blue'); // getter document.documentElement.style.getPropertyValue('--myVariable');
However, if the value of var has been set using .setProperty()
, the getter will only return that value.
If set via a CSS declaration, undefined
will be returned. Check it out in this example:
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>
To avoid this unexpected behavior, you must use the getCompulatedStyle()
method before calling .getPropertyValue()
.
The getter will then look like this:
getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');
In my opinion, accessing CSS variables should be simpler, faster, intuitive and natural...
I implemented CSSGlobalVariables
a small (<3kb) javascript helper that automatically detects all active CSS global variables in the document and packages them into an object, <3kb) javascript 帮助程序,它自动检测文档中所有活动的 CSS 全局变量并将其打包到一个对象中, for easier Access and Operation< /strong>.
// 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 );
Any changes applied to object properties are automatically converted to CSS variables.
Available: https://github.com/colxi/ css-global variables
P粉8632950572023-10-21 14:23:27
You can use 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