JavaScript로 CSS 변경 변수
JavaScript로 변수 변경
CSS 변수는 DOM에 액세스할 수 있으므로 JavaScript로 변경할 수 있습니다.
다음은 이전 페이지에서 사용한 예에서 --blue 변수를 표시하고 변경하는 스크립트를 만드는 방법의 예입니다. 지금은 JavaScript에 익숙하지 않더라도 걱정하지 마십시오. JavaScript 자습서 에서 JavaScript에 대해 자세히 알아볼 수 있습니다 .
예시
<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>
브라우저 지원
표의 숫자는
var()
기능을 완전히 지원하는 첫 번째 브라우저 버전을 지정합니다.
Function | |||||
---|---|---|---|---|---|
var() | 49.0 | 15.0 | 31.0 | 9.1 | 36.0 |
CSS var() 함수
Property | Description |
---|---|
var() | Inserts the value of a CSS variable |