js4-2

by wang_siang

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/vanilla-lazyload/19.1.3/lazyload.min.js"></script>
  <img alt="A lazy image" class="lazy"
        data-src="https://images.unsplash.com/photo-1739909198159-a834175bd911?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" />
    <img alt="A lazy image" class="lazy"
        data-src="https://images.unsplash.com/photo-1518600593288-2ec370b80cba?q=80&w=2069&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" />
    <img alt="A lazy image" class="lazy"
        data-src="https://images.unsplash.com/photo-1641317136698-284db1e10c1b?q=80&w=2071&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" />
    <img alt="A lazy image" class="lazy"
        data-src="https://images.unsplash.com/photo-1728044849316-b42a4b25e507?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" />
    <img alt="A lazy image" class="lazy"
        data-src="https://images.unsplash.com/photo-1726064855857-4540ed3834db?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" />
    <img alt="A lazy image" class="lazy"
        data-src="https://images.unsplash.com/photo-1740031904427-ca6713523372?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" />
    <img alt="A lazy image" class="lazy"
        data-src="https://images.unsplash.com/photo-1740130768424-10c4fb1daaac?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" />
    <img alt="A lazy image" class="lazy"
        data-src="https://images.unsplash.com/photo-1731835459953-1033df3ca6bf?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" />
    <img alt="A lazy image" class="lazy"
       ...

CSS

img {
            width: 100%;
            height: 100vh;
            margin-bottom: 20px;
        }

        img.lazy {
            opacity: 0;
        }

        img:not(.initial) {
            transition: opacity 5s;
        }

        img.initial,
        img.loaded,
        img.error {
            opacity: 1;
        }

        img:not([src]) {
            visibility: hidden;
        }

JavaScript

var lazyLoadInstance = new LazyLoad({
            // elements_selector: ".lazy", // 目標元素
            // callback_enter: initOneLazyLoad,// 當目標元素進入視口時,觸發 initOneLazyLoad 函數
            // unobserve_entered: true// 一旦元素進入視口,就停止觀察這些元素
        });

        // function initOneLazyLoad(element) {
        //     element.classList.add('loaded');
        // }