CSS-Änderungsvariablen mit JavaScript
Variablen mit JavaScript ändern
CSS-Variablen haben Zugriff auf das DOM, was bedeutet, dass Sie sie mit JavaScript ändern können.
Hier ist ein Beispiel dafür, wie Sie ein Skript erstellen können, um die Variable --blue aus dem auf den vorherigen Seiten verwendeten Beispiel anzuzeigen und zu ändern. Machen Sie sich vorerst keine Sorgen, wenn Sie mit JavaScript nicht vertraut sind. Mehr über JavaScript erfahren Sie in unserem JavaScript-Tutorial :
Beispiel
<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>
Browser-Unterstützung
Die Zahlen in der Tabelle geben die erste Browserversion an, die die
var()
Funktion vollständig unterstützt.
Function | |||||
---|---|---|---|---|---|
var() | 49.0 | 15.0 | 31.0 | 9.1 | 36.0 |
CSS-var()-Funktion
Property | Description |
---|---|
var() | Inserts the value of a CSS variable |