Intersection Observer를 활용한 스크롤 애니메이션

CSS 24.02.26


Intersection Observer를 사용하여 스크롤 애니메이션을 만들려면 다음과 같은 단계를 따를 수 있습니다.


HTML 구조 설정

애니메이션을 적용할 요소들을 HTML에 추가합니다.


CSS 스타일링

애니메이션에 필요한 스타일을 CSS로 정의합니다.


JavaScript로 Intersection Observer 구현

Intersection Observer를 사용하여 스크롤 이벤트를 감지하고, 해당 요소가 화면에 보이는지 여부를 확인합니다.


필요에 따라 애니메이션 효과 추가

요소가 화면에 나타나거나 사라질 때 발생하는 애니메이션을 추가합니다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scroll Animation with Intersection Observer</title>
<style>
  .box {
    width: 100px;
    height: 100px;
    background-color: red;
    margin: 50px auto;
    opacity: 0;
    transition: opacity 0.5s ease;
  }
  .show {
    opacity: 1;
  }
</style>
</head>
<body>
<div class="box"></div>
<div style="height: 1000px;"></div> 
<script>
  const boxes = document.querySelectorAll('.box');
 
  const options = {
    root: null,
    rootMargin: '0px',
    threshold: 0.5 // 뷰포트의 50% 이상이 요소와 교차할 때
  };
 
  const observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('show');
        observer.unobserve(entry.target); // 애니메이션이 한 번만 트리거 되도록 관찰 중단
      }
    });
  }, options);
 
  boxes.forEach(box => {
    observer.observe(box);
  });
</script>
</body>
</html>
 
cs


예제


 

See the Pen Intersection Observer by designkits (@designkits) on CodePen.

목록으로
© 디자인키트