Accessing CSS Custom Properties with JavaScript
JavaScript provides methods for accessing and manipulating CSS custom properties, also known as CSS variables. Unlike regular CSS properties, these custom properties are accessible through the var(...) syntax in the stylesheet.
Getting Custom Property Values
To retrieve the value of a custom property, use window.getComputedStyle(document.body).getPropertyValue('--name'), where --name is the custom property name. For example:
var bodyStyles = window.getComputedStyle(document.body); var fooBar = bodyStyles.getPropertyValue('--foo-bar');
Setting Custom Property Values
To set a custom property value, use document.body.style.setProperty('--name', value), where --name is the custom property name and value is the new value. For example:
document.body.style.setProperty('--foo-bar', 'red');
Example
Consider the following code:
<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.setProperty('--mycolor', 'red'); document.body.style['font-weight'] = 'bold'; }; function jQuery_() { $('body').css('--mycolor', 'red'); $('body').css('font-weight', 'bold'); } </script> </body>
Clicking the "Plain JS" or "jQuery" button will now set the --mycolor custom property to red and bold the text.
The above is the detailed content of How Can JavaScript Access and Modify CSS Custom Properties?. For more information, please follow other related articles on the PHP Chinese website!