2025年使用IntersectionObserver 實現惰性加载(demo)

使用IntersectionObserver 實現惰性加载(demo)lt DOCTYPE html gt lt html lang en gt lt head gt lt meta charset UTF 8 gt lt meta name viewport content

大家好,我是讯享网,很高兴认识大家。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .main { 
    width: 50%; } .img { 
    display: block; height: 200px; width: 200px; margin: 10px auto; } </style> </head> <body> <div class="main"> <img class="img" src="" alt=""> <img class="img" src="" alt=""> <img class="img" src="" alt=""> <img class="img" src="" alt=""> <img class="img" src="" alt=""> <img class="img" src="" alt=""> </div> </body> <script> let array = [ 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fa2.att.hudong.com%2F27%2F81%2F0023076.jpg&refer=http%3A%2F%2Fa2.att.hudong.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=&t=d642abbbc5b984f0a3591b1a1d', 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fa0.att.hudong.com%2F52%2F62%2F.jpg&refer=http%3A%2F%2Fa0.att.hudong.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=&t=929bb81f04613d98a6dfcda6ca', 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fa3.att.hudong.com%2F35%2F34%2F.jpg&refer=http%3A%2F%2Fa3.att.hudong.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=&t=ffa3a424fabacc7f182', 'https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/9c16fdfaaf51f3de9ba8ee1194eef01f3a2979a8.jpg', 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.aiimg.com%2Fuploads%2Fuserup%2F0909%2F2Z64022L38.jpg&refer=http%3A%2F%2Fimg.aiimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=&t=2063f669ff6a25f7063dee2b0c6e97ec', 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fa3.att.hudong.com%2F92%2F04%2F0000392.jpg&refer=http%3A%2F%2Fa3.att.hudong.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=&t=87bfda72fcc5ba77e090052b93a8eff1' ] for (let i = 0; i < array.length; i++) { 
    var observer = new IntersectionObserver( function (changes) { 
    changes.forEach(function (change) { 
    var container = change.target; // 相交率,默认是相对于浏览器视窗 if (change.intersectionRatio > 0) { 
    container.src = array[i] observer.unobserve(container); } }); } ); observer.observe(document.querySelectorAll('.img')[i]); } </script> </html> 

讯享网
小讯
上一篇 2025-03-01 20:57
下一篇 2025-04-08 22:27

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/73782.html