Home > Web Front-end > CSS Tutorial > How Can JavaScript Access and Modify CSS Custom Properties?

How Can JavaScript Access and Modify CSS Custom Properties?

Linda Hamilton
Release: 2024-12-09 03:01:09
Original
809 people have browsed it

How Can JavaScript Access and Modify CSS Custom Properties?

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');
Copy after login

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');
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template