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.
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 el navegador
Los números de la tabla especifican la primera versión del navegador que es totalmente compatible con la función var()
.
Función | Chrome | Edge | Mozilla | Safari | Opera |
var() | 49.0 | 15.0 | 31.0 | 9.1 | 36.0 |
La función var()
Propiedad | Descripción |
var() | Inserta el valor de una variable CSS. |
Traducido con 💚 desde W3Schools.com