intersection observer实现图片懒加载

html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./index2.css">
</head>
<body>
    <div>
        <h1>图片相册</h1>
    <img data-src="http://pic1.win4000.com/wallpaper/2018-09-19/5ba21a3006800.jpg" alt="">
    <img data-src="https://t7.baidu.com/it/u=1785207335,3397162108&fm=193&f=GIF" alt="">
    <img data-src="https://t7.baidu.com/it/u=338595665,4065109605&fm=193&f=GIF" alt="">
    <img data-src="https://t7.baidu.com/it/u=1732966997,2981886582&fm=193&f=GIF" alt="">
    <img data-src="https://t7.baidu.com/it/u=2581522032,2615939966&fm=193&f=GIF" alt="">
    <img data-src="https://t7.baidu.com/it/u=245883932,1750720125&fm=193&f=GIF" alt="">
    <img data-src="https://t7.baidu.com/it/u=3423293041,3900166648&fm=193&f=GIF" alt="">
    <img data-src="https://t7.baidu.com/it/u=3241434606,2550606435&fm=193&f=GIF" alt=""> 
    <img data-src="https://t7.baidu.com/it/u=1417505637,1247476664&fm=193&f=GIF" alt="">
    <img data-src="https://img0.baidu.com/it/u=775184654,1087701200&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500">
    <img data-src="https://lmg.jj20.com/up/allimg/1114/1110200ZS0/2011100ZS0-9-1200.jpg" alt="">
    </div>
    
</body>
<script src="./index2.js"></script>
</html>

css代码:

img{
    width: 100vw;
    transform: translateX(50%);
    opacity: 0;
    transition: all 500ms;
}

.fade{
    transform: translateX(0);
    opacity: 1;
    transition: all 500ms;
}

js代码:

const targets = document.querySelectorAll('img');
const lazyload = target =>{
    const io = new IntersectionObserver((entries,observer) =>{
        entries.forEach((entry)=>{
            console.log("load img")
            if(entry.isIntersecting){
                const img = entry.target
                const src = img.getAttribute("data-src")
                img.setAttribute("src",src);
                img.classList.add("fade")
                observer.disconnect();
            }
        })
    })
    io.observe(target)
}

targets.forEach(lazyload);

无限滚动实现:数据无限滚动使用intersection observer实现-CSDN博客

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值