스크롤 위치에 따라 HTML Element 조작하기
Prologue
요즘 잘나가는 웹 페이지를 보면 스크롤로 컨텐츠를 다르게 보여주는 것은 기본이라고 할 수 있다.
스크롤 위 아래 움직일 때마다 이미지가 다르게 보이거나 이동한다던지,
lazy loading을 구현 시에도 물론 scroll를 활용한다.
어떻게 개발 해야하는지 확인해보자.
Scroll Event
스크롤 위치 값 확인
pageYOffSet
은 위 아래로 스크롤 할때마다 문서의 현 위치를 pixel 값을 알려준다.
window.addEventListener('scroll', function() {
console.log(window.pageYOffSet)
})
Element 위치 (offsetTop)
offsetTop
으로 현 위치를 알 순 있지만, 스크롤이 되어도 값이 변하지 않는다. 즉, 처음 위치한 값만 알 수 있다.
const ele = document.querySelector('.box');
console.log(ele.offsetTop)
Element 위치 (getBoundingClientRect())
getBoundingClientRect()
를 이용하면 해당 element의 크기와 viewport 기준으로 현 위치를 알 수 있다.
const ele = document.querySelector('.box');
console.log(ele.getBoundingClientRect())
스크롤에 따라 element 위치 확인
getBoundingClientRect()
를 이용하여 element 위치를 동적으로 알 수 있고, window.innerHeight
를 이용하여 스크롤 영역? 포함한 브라우저 창 크기를 알아내어 이 두개의 값으로 구현 가능하다
const ele = document.querySelector('.box');
const y = ele.getBoundingClientRect().top
if (y < window.innerHeight * 0.5) {
...
}
참고
pageYOffset official
getBoundingClientRect() official
Window.innerHeight official