IntersectionObserver实现图片懒加载 - 前端笔记-注意几点;1.图片需要有高度,2.可视区需要有高度 !DOCTYPE html html lang=en head ...

学习笔记

点滴记忆
回忆过往
首页>> web前端 >>IntersectionObserver实现图片懒加载 - 前端笔记
注意几点;1.图片需要有高度,2.可视区需要有高度





<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<style>
    * {
        margin: 0;
        padding: 0;
    }
    img {
        min-height: 900px;
    }
</style>
<div class="namdda" style="height: 100vh;overflow-y: scroll;">
    <img data-img="https://blog.dbsgw.com/content/templates/Fys/images/random/1.jpg" style="width: 100%">
    <img data-img="https://blog.dbsgw.com/content/templates/Fys/images/random/2.jpg" style="width: 100%">
    <img data-img="https://blog.dbsgw.com/content/templates/Fys/images/random/3.jpg" style="width: 100%">
    <img data-img="https://blog.dbsgw.com/content/templates/Fys/images/random/4.jpg" style="width: 100%">
    <img data-img="https://blog.dbsgw.com/content/templates/Fys/images/random/5.jpg" style="width: 100%">
    <img data-img="https://blog.dbsgw.com/content/templates/Fys/images/random/6.jpg" style="width: 100%">
    <img data-img="https://blog.dbsgw.com/content/templates/Fys/images/random/7.jpg" style="width: 100%">
    <img data-img="https://blog.dbsgw.com/content/templates/Fys/images/random/8.jpg" style="width: 100%">
    <img data-img="https://blog.dbsgw.com/content/templates/Fys/images/random/9.jpg" style="width: 100%">
    <img data-img="https://blog.dbsgw.com/content/templates/Fys/images/random/10.jpg" style="width: 100%">
</div>

<script>

    const io = new IntersectionObserver((res) => {
            console.log(res, "reds")
            res.forEach((v) => {
                if (v.isIntersecting) {
                    // 图片详情
                    const {img, key} = v.target.dataset;
                    console.log(v, v.target)
                    // 把 图片的img 赋值给 src
                    v.target.src = img;
                    // 图片加载完成
                    v.target.onload = () => {
                        io.unobserve(v.target);
                    };
                }
            });
        }, {
            root: document.querySelector('.namdda'),
// 这里是一个数组可以指定多个比例类似[0.25, 0.5, 0.75, 1]
            threshold: [0],//交会处
            rootMargin: "0px"
        }//对视口进行收缩和扩张
    );
    Array.from(document.querySelectorAll('img')).forEach((img) => io.observe(img));
</script>
</body>
</html>


×

感谢您的支持,我们会一直保持!

扫码支持
请土豪扫码随意打赏

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

打赏作者
版权所有,转载注意明处:前端笔记 » IntersectionObserver实现图片懒加载

发表评论

路人甲 表情
Ctrl+Enter快速提交

网友评论(0)