JS | IntersectionObserver 使用滚动 动画渐显 元素

in 前端CSS系列 with 0 comment

参考效果地址

https://surest-sky.github.io/web/intersection.html

使用例子

window.addEventListener('load', () => {

    let options = {
        rootMargin: "0px",
        threshold: 0.3,
    };
    const infiniteCallback = (entries, observer) => {
        entries.forEach((entry) => {
            if (entry.isIntersecting) {
                console.log(entry)
                // stop observer and load the image
                const lazyImage = entry.target;
                console.log("lazy loading ", lazyImage);
                lazyImage.setAttribute("src", "https://i.picsum.photos/id/1023/400/400.jpg?hmac=maIZbUj7YZWazRxkpv3aiALni4kh_xYP1Vzkf28IvhA")
                const isC = lazyImage.getAttribute("data-class")
                lazyImage.classList.add(isC)
                // observer.unobserve(entry.target);
                setTimeout(() => {
                    lazyImage.classList.remove(isC)
                }, 1000)
            }
        });
    }

    loaderObserver = new IntersectionObserver(
        infiniteCallback,
        options
    );
    console.log(document.querySelectorAll("img"))

    const images = document.querySelectorAll("img");
    Array.from(images).map(image => {
        loaderObserver.observe(image);
    })
})

源码

https://github.com/surest-sky/surest-sky.github.io/blob/master/web/intersection.html

Comments are closed.