JS30 22강을 진행하면서 배운 내용을 정리해두려 합니다.
1. getBoundingClientRect()
https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
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
이번 프로젝트를 진행하면서 특정 DOM 요소의 x,y 위치를 offsetTop offsetLeft 만 이용해서 구했는데 사실 getBoundingClientRect 메서드를 쓰면 더 간단한거였다.
getBoundingClientRect의 경우 viewport 기준으로 x, y를 알려주기 때문에 현재 보여지는 화면에서의 위치를 구하기 편하다. (단 마우스 스크롤 등으로 요소가 움직일경우 x, y 좌표값에 window.scollY 등으로 해당 수치를 조정해줘야함.)
한가지 헷갈렸던점은 offsetParent가 정확히 무엇인지였는데
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.wrapper {
position: relative;
}
</style>
</head>
<body>
<div class="test"></div>
<div class="wrapper">
<a href="">test2</a>
</div>
</body>
<script>
console.log(document.querySelector('.test').offsetParent) //<body>
console.log(document.querySelector('a').offsetParent) //<div class="wrapper">
</script>
</html>
MDN문서의 정의를 보면 "closest positioned ancestor 가 offset parent다" 라고 나와있다.
나는 지금까지 DOM 트리에서 Ancestor는 가장 상위에있는 body 만 지칭하는거라고 생각했었는데 그게 아니고. 바로위에있는 parent도 경우에 따라 ancestor가 되는 것을 알게 되었다.
'TIL > HTML, CSS, JS 이것저것' 카테고리의 다른 글
JS30-Stripe Follow Along Dropdown (0) | 2021.06.24 |
---|---|
JS30- Sticky Nav / Event Capture, propagation (0) | 2021.06.23 |
JS30-Local storage, Mouse Move, Sort (0) | 2021.06.16 |
JS30-Slide in on Scroll (0) | 2021.06.15 |
JS30-Video Player (0) | 2021.06.12 |
댓글