CSS Using JavaScript to Change Variable

Baguhin ang variable gamit ang JavaScript

Maaaring ma-access ng CSS variable ang DOM, ibig sabihin maaring baguhin sila gamit ang JavaScript.

Ang eksemplo na ito ay nagpapakita kung paano gumawa ng script upang ipakita at baguhin ang variable na --blue na ginamit sa nakaraang pahina. Kung hindi ka naiintindihan ang JavaScript, huwag mag-alala. Maaari mong matututuhan ang higit pang kaalaman tungkol sa JavaScript sa aming tutorial sa JavaScript:

Mga Halimbawa

<script>
// Get the root element
var r = document.querySelector(':root');
// Create a function to get the value of the variable
function myFunction_get() {
  // Get the styles (properties and values) for the root
  var rs = getComputedStyle(r);
  // Alert the value of the --blue variable
  alert("Ang halaga ng --blue ay: " + rs.getPropertyValue('--blue'));
}
// Create a function to set the value of the variable
function myFunction_set() {
  // Set the value of variable --blue to another value (in this case "lightblue")
  r.style.setProperty('--blue', 'lightblue');
}
</script>

Try It Yourself

Browser Support

The numbers in the table indicate the first browser version that fully supports this attribute.

Function
var() 49.0 15.0 31.0 9.1 36.0

CSS var() Function

Function Description
var() Insert the value of the CSS variable.