개발관련/자바스크립트 팁

그래서 Top 이 어딘데? getBoundingClientRect().top element.offsetTop 차이점

개발자 Dane 2021. 5. 11. 00:24
반응형

TOP 에는 여러 종류가 있습니다.

 

커피?

 

롤?

 

 

 

JAVASCRIPT 에서 TOP을 구하는 방법은 여러가지가 있습니다.

offsetTop, getClientRects().top 매번 프론트엔드 UI, 애니메이션을 개발 할 때는 Element의 좌표가 중요한데 항상 헷갈리는 부분입니다. 이번 기회에 확실하게 각 차이점이 무엇인지 알아보고 어떤 경우에 사용하는지 확인해보겠습니다.

 

위 그림처럼 div를 배치 했습니다.

https://stackblitz.com/edit/js-xtkggx?file=index.js

const inner = document.getElementById('inner');
console.log('inner.top', inner.offsetTop);
console.log('inner.top', inner.getBoundingClientRect().top);

const other = document.getElementById('other');
console.log('other.top', other.offsetTop);
console.log('other.top', other.getBoundingClientRect().top);

 

위와 같은 코드로 각각의 top좌표를 구합니다.

 

동일한 DIV의 TOP 좌표를 구하는 것인데도 결과는 각각 다릅니다.

 

왜 눈물이 날까

 

그만큼 기준이 중요합니다.

 


 

getBoundingClientRect().top

 

viewport 즉 현재 보이는 화면을 기준으로 하는 좌표값을 반환합니다.

현재 화면을 기준으로 하기 때문에 scroll 위치등에 따라 값이 변합니다.

실시간 동적으로 움직이는 좌표를 구할때도 좋습니다.

 

반응형

offsetTop

부모 요소에게서 상대적인 top좌표를 반환합니다. 여기서 중요한건 position이 relative인 부모 요소 만을 찾아서 기준으로 삼습니다. 만약에 부모 요소중에 position이 relative가 없다면 최상위 dom을 기준으로한 좌표를 반환합니다. 즉 절대좌표입니다.

 

절대좌표

const absoluteTop = window.pageYOffset + element.getBoundingClientRect().top;

getBoundingClientRect를 이용해서 안전하게 절대 좌표를 구하는 방법입니다.

 

👉 elment의 position이 fixed라면?

position이 fixed라면 부모의 position에 영향을 받지 않기 때문에 offsetTop은 절대 좌표가 되고 viewport에서 항상 동일한 위치에 있기 때문에 getBoundingClientRect().top과 같은 값을 반환합니다.


👍 결론

다음 포스팅은 위 메소드를 이용해서 작성한 애니메이션 효과에 대해서 작성할 예정입니다. 이해가 안되거나 더 궁금하신 점이 있다면 댓글로 남겨 주세요. 감사합니다.

 

 

 

참고 사이트 

Element.getBoundingClientRect() - Web APIs | MDN

 

Element.getBoundingClientRect() - Web APIs | MDN

The Element.getBoundingClientRect() method returns a DOMRect object providing information about the size of an element and its position relative to the viewport.

developer.mozilla.org

 

HTMLElement.offsetTop - Web APIs | MDN

 

HTMLElement.offsetTop - Web APIs | MDN

The HTMLElement.offsetTop read-only property returns the distance of the outer border of the current element relative to the inner border of the top of the offsetParent node.

developer.mozilla.org

p.s

나폴레옹은 실제로는 키가 작지 않았다고 합니다.

반응형