[javascript] ScrollReveal을 활용한 스크롤 숨김/표시 효과 구현 방법

많은 웹사이트에서는 사용자가 스크롤을 내리면 요소들이 부드럽게 나타나거나 사라지는 효과를 구현하는 것을 볼 수 있습니다. 이러한 효과를 만들기 위해서는 ScrollReveal 라이브러리를 사용할 수 있습니다. 이 라이브러리는 스크롤 이벤트를 감지하여 요소들을 동적으로 제어할 수 있게 해줍니다.

ScrollReveal 라이브러리 설치

우선, ScrollReveal 라이브러리를 설치해야 합니다. 아래의 명령어를 사용하여 npm을 통해 라이브러리를 설치할 수 있습니다.

npm install scrollreveal

ScrollReveal 사용법

  1. ScrollReveal 라이브러리를 가져옵니다.
import ScrollReveal from 'scrollreveal';
  1. 스크롤 효과를 부여하고자 하는 요소들을 선택합니다.
const revealElements = document.querySelectorAll('.reveal');
  1. ScrollReveal 객체를 생성하고 설정값을 지정합니다.
const scrollReveal = ScrollReveal({
  distance: '30px',   // 요소의 이동 거리
  duration: 1000,     // 애니메이션 지속 시간 (밀리초)
  easing: 'ease',     // 애니메이션 속도 곡선 (linear, ease, ease-in, ease-in-out 등)
  origin: 'bottom',   // 요소가 나타날 기준점 (top, bottom, left, right, center)
  reset: true         // 요소가 숨겨졌다가 다시 나타날 때 애니메이션을 다시 시작할지 여부
});
  1. 요소를 숨기거나 나타낼 애니메이션을 설정합니다.
scrollReveal.reveal(revealElements, {
  delay: 200,         // 애니메이션 시작 전 지연 시간 (밀리초)
  interval: 200,      // 각 애니메이션 간의 지연 시간 (밀리초)
  mobile: false       // 모바일 기기에서도 동작할지 여부
});

예제

<!DOCTYPE html>
<html>
<head>
  <title>ScrollReveal Example</title>
  <style>
    .reveal {
      opacity: 0;
    }
  </style>
</head>
<body>
  <h1>ScrollReveal Example</h1>

  <div class="reveal">이 요소는 스크롤 효과를 가지고 있습니다.</div>
  <div class="reveal">이 요소도 동일하게 나타납니다.</div>

  <script>
    import ScrollReveal from 'scrollreveal';

    const revealElements = document.querySelectorAll('.reveal');

    const scrollReveal = ScrollReveal({
      distance: '30px',
      duration: 1000,
      easing: 'ease',
      origin: 'bottom',
      reset: true
    });

    scrollReveal.reveal(revealElements, {
      delay: 200,
      interval: 200,
      mobile: false
    });
  </script>
</body>
</html>

위의 예제 코드를 실행하면 스크롤을 내리면 .reveal 클래스를 가진 요소들이 부드럽게 나타나는 효과를 볼 수 있습니다.

ScrollReveal 라이브러리를 사용하면 웹사이트에서 스크롤에 반응하는 동적인 효과를 구현할 수 있습니다. 자세한 사용 방법과 다양한 설정값에 대해서는 공식 문서를 참고하시기 바랍니다.