JS/jQuery - 스크립트로 inline-style, css (변수 포함) 제어하기
2024. 7. 5.
목차

Style 제어하기
웹페이지에서 스크립트로 요소의 스타일을 동적으로 제어할 수 있다. 값을 가져올 수도 있고, 추가 하거나 제거 할 수도 있다. 버튼을 클릭하면 변경되어야 하는 경우처럼 필요에 따라 사용할 수 있다.
바닐라 스크립트
// window.getComputedStyle() 메소드로 전체 CSS 변수의 현재 값을 가져옴. const rootStyles = window.getComputedStyle(document.documentElement); // getPropertyValue 메소드로 변경 할 변수 또는 속성값을 선택. const mainColorValue = rootStyles.getPropertyValue('--main-color'); const heightValue = rootStyles.getPropertyValue('height'); // document.querySelector() 메소드로 CSS 변수를 설정할 요소를 선택. const targetElement = document.querySelector('.target-element'); // element.style.setProperty() 메소드로 변수 또는 속성값 변경 targetElement.style.setProperty('--main-color', 'red'); targetElement.style.setProperty('height', '150px');
getComputedStyle() | 선택한 요소의 모든 CSS 속성값을 제어한다. 속성의 인라인 스타일로 지정한 속성값과 외부 스타일시트에서 지정한 속성값을 모두 가져올 수 있다. :root과 같이 가상 클래스에 지정되어 있는 값도 가져온다. |
---|---|
element.style | 선택한 요소의 인라인스타일로 지정된 style값을 제어한다. |
예시
See the Pen Vanilla js - css, inline-style (--variable) change by 슬기 (@hahahoho9) on CodePen.
제이쿼리
// 요소의 스타일 값 가져오기. const mainColorValue = $(':root').css('--main-color'); const heightValue = $(':root').css('height'); // $(element).css 메소드로 스타일 변경. $('.target-element').css('--main-color', 'red'); $('.target-element').css('--font-size', '20px');