HTML+CSS实现懒加载,只需简单JS真的简单!

HTML部分

<h1>元素进入视口时的动画示例</h1>
    <p>向下滚动以查看元素动画效果。</p>

    <div class="box animate-on-scroll">Box 1</div>
    <div class="box animate-on-scroll">Box 2</div>
    <div class="box animate-on-scroll">Box 3</div>
    <div class="box animate-on-scroll">Box 4</div>
    <div class="box animate-on-scroll">Box 5</div>

CSS部分

body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            line-height: 1.6;
        }

        .animate-on-scroll {
            opacity: 0;
            transform: translateY(50px);
            transition: opacity 0.5s, transform 0.5s;
        }

        .animate-on-scroll.animate {
            opacity: 1;
            transform: translateY(0);
        }

        .box {
            width: 200px;
            height: 200px;
            background-color: #4CAF50;
            margin: 50px auto;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
            font-size: 24px;
        }

JS

<script>
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('animate');
                }
            });
        }, {
            threshold: 0.1
        });

        document.querySelectorAll('.animate-on-scroll').forEach((el) => {
            observer.observe(el);
        });
    </script>

综上:效果实现啦!

THE END