
JS로 CCS 스타일의 속성값을 알아낼 수 있는 짝꿍을 소개합니다!
getComputedStyle와 getPropertyValue입니다.
getComputedStyle은 객체형태로 반환해주고 getPropertyValue로 속성값을 가져올 수 있다고 합니다.
getComputedStyle 구문
var style = window.getComputedStyle(element[, pseudoElt]);
* element : 속성값을 얻으려는 요소
* pseudoElt : 의사요소(=pseudo-elements, ::after, ::before, ::marker등등... )를 지정하는 문자열. 보통 생략되거나 null이어야 함
getComutedStyle 구문
매개변수로 지정된 CSS속성의 값을 반환합니다.
var value = element.style.getPropertyValue(property);
예시
<p>study</p>
p {
width: 400px;
margin: 0 auto;
padding: 20px;
line-height: 2;
font-size: 2rem;
font-family: sans-serif;
background: green;
color: white;
text-align: center;
}
let para = document.querySelector('p');
let compStyles = window.getComputedStyle(para);
para.textContent = 'My computed font-size is ' + compStyles.getPropertyValue('font-size') +
', and my computed line-height is ' + compStyles.getPropertyValue('line-height') + '.';
결과는 아래와 같이 나옵니다.
좀 감이 옵니다...!!?

'JAVA SCRIPT' 카테고리의 다른 글
[JS] querySelector vs getElementById중 무엇을 사용해야 할까? (0) | 2023.02.03 |
---|---|
[JS] JSON (0) | 2023.01.14 |
[일반] 객체, 클래스, 인스턴스의 개념 (1) | 2023.01.09 |
[JS] 쌍따옴표(")와 홑따옴표(')에 대해서 (0) | 2023.01.05 |
[JS] 화살표 함수 (0) | 2022.12.27 |