Changing CSS :root Color Variables in JavaScript
In the realm of web development, customizing the visual aesthetics of a webpage is often accomplished through the use of CSS variables. These variables, defined within the :root section of the CSS, enable developers to control various aspects of the design. One common scenario is the ability to change these colors dynamically using JavaScript.
To achieve this, the key piece of code is:
document.documentElement.style.setProperty('--your-variable', '#YOURCOLOR');
This line essentially modifies the specified CSS variable in the :root section, updating its value to the desired color. For instance, if you want to change the --main-color variable to black, you would use the following code:
document.documentElement.style.setProperty('--main-color', '#000000');
Applying this code to the example provided in the question:
function setTheme(theme) { if (theme == 'Dark') { localStorage.setItem('panelTheme', theme); $('#current-theme').text(theme); document.documentElement.style.setProperty('--main-color', '#000000'); } if (theme == 'Blue') { localStorage.setItem('panelTheme', 'Blue'); $('#current-theme').text('Blue'); alert("Blue"); } if (theme == 'Green') { localStorage.setItem('panelTheme', 'Green'); $('#current-theme').text('Green'); alert("Green"); } }
This updated code successfully modifies the --main-color variable and dynamically changes the colors on the webpage when a button is clicked.
The above is the detailed content of How to Dynamically Change CSS :root Color Variables with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!