HMLT&CSS&JS/javascript

[API]IntersectionObserver

turfrain 2024. 5. 16. 12:08

new IntersectionObserver(callback[, options]);

Intersection Observer API 의 IntersectionObserver 인터페이스는 대상 요소와 상위 요소, 또는 대상 요소와 최상위 문서의 뷰포트 가 서로 교차하는 영역이 달라지는 경우 이를 비동기적으로 감지할 수 있는 수단을 제공합니다.

DOC : https://developer.mozilla.org/ko/docs/Web/API/IntersectionObserver

 

메서드 설명
.observe(targetElement) 루트 내에서의 가시성 변화를 감지할 element입니다. 루트 요소의 자손이어야 합니다. 루트가 현재 문서의 뷰포트일 경우 이 요소도 문서 내에 위치해야 합니다.
반환값 : undefined
.disconnect() IntersectionObserver의 disconnect() 메서드는 감지기의 모든 가시성 변화 주시 대상을 해제합니다.
반환값 : undefined

 

속성  설명
.isIntersecting 화면에 보이면 true, 벗어나면 false
.intersectionRatio 거리를 퍼센티지로 (0 ~ 1)

 

- 사용예)

const observer = new IntersectionObserver((els) => {
   els.forEach((el) => {
       if(el.isIntersecting) {
         // 화면에 들어왔을때
       }else{
         // 화면에 벗어 났을때
       }
       console.log("per: ", el.intersectionRatio)
   })
})

observer.observe( document.querySelector(".클래스") );