frontend/javascript
[Javascript] 요소의 크기 확인하기 :: offsetWidth(+ 요소의 top값 확인하기 (offsetTop)) , clientWidth, scrollWidth / offsetHeight, clientHeight, scrollHeight
meroriiDev
2021. 6. 21. 12:09
728x90
반응형
body태그나 특정 요소의 크기를 확인해야하는 경우
상황에 따라 쓰일 수 있는 세 가지의 값이 있다.
document.body.offsetWidth;
document.querySelector('.classNameSomething').offsetWidth;
● offsetWidth(Height)
document.querySelector('.classNameSomething').offsetWidth;
document.querySelector('.classNameSomething').offsetHeight;
margin을 제외한 padding값, border값까지 계산한 값
제일 많이 사용!
● offsetTop
document.querySelector('.classNameSomething').offsetTop;
부모요소의 상단으로부터 떨어진 top값을 계산한 값
부모요소로부터의 떨어진 값을 계산하는 상대적인 값이다.
따라서 요소의 절대적인 값을 계산하기 위해서는 부모의 top값도 함께 구해 더해주어야한다.
function getPosY(element){
let posY = element.offsetTop;
if(element.offsetParent){
posY += element.offsetParent.offsetTop;
}
return posY;
}
● clientWidth(Height)
document.querySelector('.classNameSomething').clientWidth;
document.querySelector('.classNameSomething').clientHeight;
margin, border를 제외하고 padding값까지 계산한 값
● scrollWidth(Height)
document.querySelector('.classNameSomething').scrollWidth;
document.querySelector('.classNameSomething').scrollHeight;
clientWidth(Height)와 기본적으로 동일하지만 스크롤 적용이 되어있을 때 가려진 전체 크기를 계산한 값
출처
728x90
반응형