CSS 변수는 DOM에 액세스 할 수 있으므로, JavaScript로 CSS 변수를 변경할 수 있습니다.
다음은 이전 페이지(Overriding Variables)에서 사용한 예제에서 --blue 변수를 표시하고 변경하는 스크립트를 만드는 방법의 예제입니다.
<!DOCTYPE html> <html lang="en"> <head> <style> :root 23; --blue: #1e90ff; --white: #ffffff; 25; body 23; background-color: var(--blue); 25; h2 23; border-bottom: 2px solid var(--blue); 25; .container 23; color: var(--blue); background-color: var(--white); padding: 15px; 25; .container button 23; background-color: var(--white); color: var(--blue); border: 1px solid var(--blue); padding: 5px; 25; </style> </head> <body> <h1>Get and Change CSS Variable With JavaScript</h1> <div class="container"> <h2>Lorem Ipsum</h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. </p> <p> <button>Yes</button> <button>No</button> </p> </div> <br> <button type="button" onclick="myFunction_get()">Get CSS Variable with JavaScript</button> <button type="button" onclick="myFunction_set()">Change CSS Variable with JavaScript</button> <script> // Get the root element let r = document.querySelector(':root'); // Create a function for getting a variable value function myFunction_get() 23; // Get the styles (properties and values) for the root let rs = getComputedStyle(r); // Alert the value of the --blue variable alert("The value of --blue is: " + rs.getPropertyValue('--blue')); 25; // Create a function for setting a variable value function myFunction_set() 23; // Set the value of variable --blue to another value (in this case "lightblue") r.style.setProperty('--blue', 'lightblue'); 25; </script> </body> </html>