JAVA SCRIPT

[JS] getComputedStyle와 getPropertyValue

해봄코딩 2023. 1. 26. 21:19

 

 

JS로 CCS 스타일의 속성값을 알아낼 수 있는 짝꿍을 소개합니다! 

getComputedStylegetPropertyValue입니다. 

 

 

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') + '.';

 

결과는 아래와 같이 나옵니다. 

 

 

 

좀 감이 옵니다...!!?