CSS Modifica variabili con JavaScript
Modifica variabili con JavaScript
Le variabili CSS hanno accesso al DOM, il che significa che puoi modificarle con JavaScript.
Ecco un esempio di come creare uno script per visualizzare e modificare la variabile --blue dall'esempio utilizzato nelle pagine precedenti. Per ora, non preoccuparti se non hai familiarità con JavaScript. Puoi saperne di più su JavaScript nel nostro tutorial JavaScript :
Esempio
<script>
// Get the root element
var r = document.querySelector(':root');
// Create a 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 --blue variable
alert("The value of --blue is: " +
rs.getPropertyValue('--blue'));
}
// Create a function for setting a
variable value
function myFunction_set() {
// Set the value of
variable --blue to another value (in this case "lightblue")
r.style.setProperty('--blue', 'lightblue');
}
</script>
Supporto browser
I numeri nella tabella specificano la prima versione del browser che supporta completamente la
var()
funzione.
Function | |||||
---|---|---|---|---|---|
var() | 49.0 | 15.0 | 31.0 | 9.1 | 36.0 |
CSS var() Funzione
Property | Description |
---|---|
var() | Inserts the value of a CSS variable |