Variáveis de mudança CSS com JavaScript
Alterar variáveis com JavaScript
As variáveis CSS têm acesso ao DOM, o que significa que você pode alterá-las com JavaScript.
Aqui está um exemplo de como você pode criar um script para exibir e alterar a variável --blue do exemplo usado nas páginas anteriores. Por enquanto, não se preocupe se você não estiver familiarizado com JavaScript. Você pode aprender mais sobre JavaScript em nosso Tutorial JavaScript :
Exemplo
<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>
Suporte ao navegador
Os números na tabela especificam a primeira versão do navegador que suporta totalmente a
var()
função.
Function | |||||
---|---|---|---|---|---|
var() | 49.0 | 15.0 | 31.0 | 9.1 | 36.0 |
Função CSS var()
Property | Description |
---|---|
var() | Inserts the value of a CSS variable |