[JavaScript] window.getComputedStyle()

홍싸리·2023년 6월 15일
0

javascript

목록 보기
14/18

window.getComputedStyle() 메소드는 인자별로 전달받은 요소의 모든 CSS 속성값을 담은 객체를 회신한다.
개별 CSS 속성값은 객체를 통해 제공되는 API 또는 CSS 속성 이름을 사용해서 간단히 색인화하여 액세스 할 수 있다.

let style = window.getComputedStyle(element[, pseudoElt]);

element

  • 속성값을 얻으려하는 요소

pseudoElt

  • 일치시킬 의사요소(pseudo element)를 지정하는 문자열. 보통의 요소들에 대해서는 생략되거나 null이어야 함

📌예제1

해당 예제에서는 간단한 <div> 요소에 CSS스타일을 적용하고, getComputedStyle()를 사용해서 적용된 스타일 값을 찾아낸 후에 <div>의 본문으로 출력한다.

<!--html-->
<p>Hello</p>
/* css */
p{
	width: 400px;
    margin: 0 auto;
    padding: 20px;
    font-size: 2rem;
    font-family: sans-serif;
    color:white;
    line-height: 2;
    text-align:center;
    background:purple;
}
//javascript
let para = document.querySelector('p');
let compStyles = window.getComputedStyle(para);
para.textContent = 'My computed font-size is ' + compStyles.getPropertyValue('font-size') + ',\nand my computed line-height is '+ compStyles.getPropertyValue('line-height') + '.';


📌예제2

<!--html-->
<div class="box"></div>
/* css */
.box{
	width:300px;
    height:300px;
    margin:50px;
    background:lightgreen;
}
//javascript
const box = document.querySelector('.box');

box.addEventListener('click', e=> {
	const bg = getComputedStyle(e.currentTarget).backgroundColor;
  	const wid = getComputedStyle(e.currentTarget).width;
	console.log(bg);
  	console.log(wid);
}
profile
그럴싸한건 다 따라해보는 프론트엔드 개발자 준비중인 6년차 퍼블리셔

0개의 댓글