programing

javascript에서 CSS 변수 접근

codeshow 2023. 9. 24. 13:12
반응형

javascript에서 CSS 변수 접근

javascript에서 cs 변수에 접근할 수 있는 방법이 있습니까?여기 내 CSS 변수 선언이 있습니다.

:root {
  --color-font-general: #336699;
}

일반적인 방법입니다.

  1. 계산된 스타일 가져오기:
  2. 원하는 속성의 값을 가져오는 데 사용합니다.
getComputedStyle(element).getPropertyValue('--color-font-general');

예:

var style = getComputedStyle(document.body)
console.log( style.getPropertyValue('--bar') ) // #336699
console.log( style.getPropertyValue('--baz') ) // calc(2px*2)
:root { --foo:#336699; --bar:var(--foo); --baz:calc(2px*2); }

사용 방법:

window.getComputedStyle(document.documentElement).getPropertyValue('--color-font-general');

이렇게 변경할 수 있습니다.

document.documentElement.style.setProperty('--color-font-general', '#000');

원천

언급URL : https://stackoverflow.com/questions/41725725/access-css-variable-from-javascript

반응형