Variables de cambio de CSS con JavaScript
Cambiar variables con JavaScript
Las variables CSS tienen acceso al DOM, lo que significa que puedes cambiarlas con JavaScript.
Este es un ejemplo de cómo puede crear un script para mostrar y cambiar la variable --blue del ejemplo utilizado en las páginas anteriores. Por ahora, no se preocupe si no está familiarizado con JavaScript. Puede obtener más información sobre JavaScript en nuestro tutorial de JavaScript :
Ejemplo
<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>
Compatibilidad con navegador
Los números de la tabla especifican la primera versión del navegador que es totalmente compatible con la
var()
función.
Function | |||||
---|---|---|---|---|---|
var() | 49.0 | 15.0 | 31.0 | 9.1 | 36.0 |
Función CSS var()
Property | Description |
---|---|
var() | Inserts the value of a CSS variable |