CSS Change Variables With JavaScript

CSS Change Variables With JavaScript

Contenido original de W3Schools


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>

Ver ejemplo


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ónChromeEdgeMozillaSafariOpera
var()49.015.031.09.136.0

La función var()

PropiedadDescripción
var()Inserta el valor de una variable CSS.

Traducido con 💚 desde W3Schools.com

Did you find this article valuable?

Support Santos Romero by becoming a sponsor. Any amount is appreciated!