How to Edit CSS Variables with JavaScript Using Style.setProperty
In CSS, variables allow you to define color themes and other settings once and use them throughout your project. To edit these variables dynamically with JavaScript, you must utilize the appropriate methods.
Incorrect Method:
In your code, you attempted to update the CSS variable using setAttribute. However, this method is invalid for editing CSS variables.
Correct Methods:
There are three correct methods to edit CSS variables with JavaScript:
documentElement.style.cssText:
documentElement.style.setProperty:
documentElement.setAttribute('style'):
Example:
To change the --main-background-color variable to red:
document.documentElement.style.cssText = "--main-background-color: red";
Demo:
<script> function changeColor() { setTimeout(() => { document.documentElement.style.cssText = "--main-background-color: red"; }, 2000); } </script>
In this demo, the background color will change to red after 2 seconds of loading the page.
The above is the detailed content of How to Correctly Modify CSS Variables Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!