Schimbarea variabilelor cu JavaScript
Deoarece variabilele CSS au acces la DOM, JavaScript le poate atât citi, cât și schimba.
Scriptul de mai jos arată o modalitate de a afișa și schimba --primary-bg-color. Tutorialul nostru de JavaScript este locul potrivit pentru a afla mai multe, dacă limbajul este încă nou pentru tine.
Exemplu
Pentru a citi variabila, scriptul apelează getComputedStyle() și apoi getPropertyValue(). Pentru a schimba valoarea, scriptul apelează style.setProperty().
Prompt
Creați o pagină HTML care folosește variabile CSS pe elementul :root (de ex. --primary-bg-color). Includeți două butoane: unul care folosește getComputedStyle și getPropertyValue pentru a afișa valoarea curentă a --primary-bg-color, și altul care folosește style.setProperty pentru a schimba --primary-bg-color în „green”. Aplicați variabila la culoarea de fundal a unui container, astfel încât schimbarea să fie vizibilă.
Output: complete HTML page
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change CSS Variables With JavaScript</title>
<style>
:root {
--primary-bg-color: coral;
}
.container {
background-color: var(--primary-bg-color);
padding: 25px;
margin: 20px 0;
}
h1 {
color: white;
}
</style>
</head>
<body>
<h1>Change CSS Variables With JavaScript</h1>
<div class="container">
<p>This container has a background color set by the CSS variable --primary-bg-color.</p>
</div>
<button onclick="myFunction_get()">Get Variable Value</button>
<button onclick="myFunction_set()">Change Variable to Green</button>
<script>
// Get the root element
var r = document.querySelector(':root');
// Function for getting a variable value
function myFunction_get() {
// Get the styles (properties and values) for the root
var rs = getComputedStyle(r);
// Alert the value of the --primary-bg-color variable
alert("The value of --primary-bg-color is: " + rs.getPropertyValue('--primary-bg-color'));
}
// Function for setting a variable value
function myFunction_set() {
// Set the value of variable --primary-bg-color to another value (in this case "green")
r.style.setProperty('--primary-bg-color', 'green');
}
</script>
</body>
</html>