JavaScript

scroll event

Yuclid 2020. 10. 12. 18:56

스크롤 이벤트에 쓰이는 몇가지 메소드, 프로퍼티를 알아보자

<div class="fixedTop">
    top
</div>
<div class="container">
    <div class="test"></div>
</div>

스크롤 이벤트는 말 그대로 웹 페이지에서 스크롤할 때 발생하는 이벤트다

(function () {
    const top = document.querySelector('.fixedTop');

    window.addEventListener('scroll', function () {
        top.innerHTML = '';
    });
})();

클릭 이벤트와 동일하게 addEventListener를 사용하고 첫번째 인자로 scroll을 주면 스크롤을 이동할 때 이벤트가 발생하게 된다

그 안에 있는 콜백 함수는 스크롤 이벤트가 발생할 때 상단에 고정되어있는 top문자열을 수정하게끔 작동한다

window.pageYOffset

    const top = document.querySelector('.fixedTop');

    window.addEventListener('scroll', function () {
        top.innerHTML = window.pageYOffset;
    });

첫 화면에서의 pageYOffset값은 0이다
스크롤을 내렸을 때의 pageYOffset 값

window객체의 프로퍼티인 pageYoffset은 스크롤이 움직일 때 윈도우의 위치를 나타낸다

object.offsetTop

    const top = document.querySelector('.fixedTop');
    const box = document.querySelector('.test');

    window.addEventListener('scroll', function () {
        top.innerHTML = box.offsetTop;
    });

처음 offsetTop의 값
스크롤을 내려도 offsetTop의 값은 같다

querySelector가져온 객체의 프로퍼티인 offsetTop은 처음 객체의 위치를 가져온다

여기서는 빨간색 박스의 객체를 받아와서 offsetTop을 출력했기 때문에 박스의 첫 위치를 가르키고 있다

object.getBoundingClientRect()

    const top = document.querySelector('.fixedTop');
    const box = document.querySelector('.test');

    window.addEventListener('scroll', function () {
        top.innerHTML = box.getBoundingClientRect().top;
    });
})();

이번에 알아볼 것은 프로퍼티가아니라 메서드인데

getBoundingClientRect는 객체를 가져온다 그럼 이 객체가 무엇인지 먼저 살펴보자

getBoundingClientRect로 가져온 객체 값

이 객체는 box의 정보를 담고 있는데 우리가 스크롤 이벤트에서 눈 여겨 봐야할 프로퍼티는 left, top과 x, y이다

눈치챘을 수도 있겠지만 left는 x와 top은 y와 동일한데

몇몇 브라우저에서는 x,y를 지원하지 않는다

이 값들은 스크롤을 상하좌우로 움직일 때 같이 값이 변하는 프로퍼티이다

box에 getBoundingClientRect메소드를 사용한 뒤에 top값을 가져와서 출력해보자

첫 화면에서 getBoundingClientRect로 가져온 객체의 top값
스크롤을 내렸을 때의 top값