Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript로 CSS 변수 읽고 쓰기 – getComputedStyle()과 setProperty() 완벽 가이드

웹 개발에서 CSS 변수(CSS 사용자 지정 속성)를 동적으로 제어하면 테마 변경, 인터랙티브 효과 등을 손쉽게 구현할 수 있습니다. JavaScript에서는 다음 세 가지 핵심 메서드만 기억하면 됩니다.

  • getComputedStyle() – 대상 요소에 적용된 모든 스타일 정보를 담고 있는 객체를 반환합니다.
  • getPropertyValue() – 계산된 스타일 객체에서 원하는 속성 값을 가져올 때 사용합니다.
  • setProperty() – CSS 변수의 값을 새로 지정하거나 변경할 때 사용합니다.

아래 예제들을 통해 CSS 변수를 가져오고 설정하는 방법을 자세히 살펴보겠습니다.

예제 1: CSS 변수 값 읽기 및 변경하기

다음 예제는 :root에 선언된 --innerColor 변수를 활용합니다. 마우스 포인터를 div 위에 올리면 현재 저장된 색상 값을 화면에 표시하고, 마우스가 벗어나면 setProperty()를 통해 배경색이 magenta로 변경됩니다.

<!DOCTYPE html>
<html>
<head>
<style>
:root {
    --outerColor: magenta;
    --innerColor: lightgreen;
    text-align: center;
}
div {
    margin: 5%;
    padding: 10%;
    background-color: var(--innerColor);
    border: 2px groove var(--outerColor);
}
</style>
</head>
<body>
<div onmouseover="showColor()" onmouseout="changeColor()">
<p></p>
</div>
</body>
<script>
let ele = document.querySelector(':root');
let para = document.querySelector('p');
function showColor() {
    let cs = getComputedStyle(ele);
    para.textContent = ("Previously " + cs.getPropertyValue('--innerColor') + " color");
}
function changeColor() {
    let item = document.querySelector('div');
    item.style.setProperty('--innerColor', 'magenta')
}
</script>
</html>

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다 −

JavaScript로 CSS 변수 읽고 쓰기 – getComputedStyle()과 setProperty() 완벽 가이드

마우스를 div 위에 올리면 getPropertyValue()가 읽어 온 이전 색상(lightgreen)이 문단에 표시되고, 마우스가 벗어나면 배경색이 magenta로 바뀌는 것을 확인할 수 있습니다.

예제 2: 조건에 따라 CSS 변수 토글하기

이번 예제는 현재 변수 값을 먼저 확인한 뒤, 조건이 충족될 때만 값을 변경하는 패턴을 보여줍니다. div에 마우스를 올리면 --customColor 값이 blue가 아닐 경우에만 blue로 전환됩니다.

<!DOCTYPE html>
<html>
<head>
<style>
:root {
    --customColor: seagreen;
}
div {
    margin: 5%;
    width: 130px;
    height: 130px;
    box-shadow: inset 0 0 38px var(--customColor);
    border-radius: 50%;
}
</style>
</head>
<body>
<div onmouseover="toggle()"></div>
</body>
<script>
let ele = document.querySelector(':root');
function toggle() {
    let cs = getComputedStyle(ele);
    let item = document.querySelector('div');
    if(cs.getPropertyValue('--customColor') !== 'blue') {
        item.style.setProperty('--customColor', 'blue')
    }
}
</script>
</html>

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다 −

JavaScript로 CSS 변수 읽고 쓰기 – getComputedStyle()과 setProperty() 완벽 가이드

원형 div에 마우스를 올리면 내부 그림자(box-shadow) 색상이 seagreen에서 blue로 부드럽게 전환됩니다.

정리

CSS 변수를 JavaScript로 제어하는 과정은 크게 두 단계로 나눌 수 있습니다. 먼저 getComputedStyle()로 스타일 객체를 얻은 후 getPropertyValue()로 현재 값을 읽고, 변경이 필요할 때는 setProperty()로 새 값을 지정하면 됩니다. 이 패턴을 활용하면 다크 모드 전환, 실시간 테마 커스터마이징 등 다양한 동적 스타일링 기능을 간단하게 구현할 수 있습니다.