ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## jquery 实例 ``` <img class="js-lazy" data-src="https://img02.sogoucdn.com/app/a/100520146/c0183d183e11944d318ab8b21726fa9d" alt="UTOOLS1596606760927.png" title="UTOOLS1596606760927.png" /> <img class="js-lazy" data-src="https://img01.sogoucdn.com/app/a/100520146/7072191df440036df1ffafe3d62687a3" alt="UTOOLS1596606740452.png" title="UTOOLS1596606740452.png" /> <img class="js-lazy" data-src="https://user-gold-cdn.xitu.io/2020/7/30/1739da4e794a1e0e?w=1199&h=439&f=png&s=34520" alt="UTOOLS1596077698036.png" title="UTOOLS1596077698036.png" /> <img class="js-lazy" data-src="https://user-gold-cdn.xitu.io/2020/7/30/1739da45ac378e00?w=672&h=423&f=png&s=35637" alt="UTOOLS1596077661990.png" title="UTOOLS1596077661990.png" /> <img class="js-lazy" data-src="https://user-gold-cdn.xitu.io/2020/7/30/1739da383454476e?w=1897&h=660&f=png&s=60027" alt="UTOOLS1596077606801.png" title="UTOOLS1596077606801.png" /> <img class="js-lazy" data-src="https://user-gold-cdn.xitu.io/2020/7/30/1739da2cb19210dd?w=1695&h=330&f=png&s=25384" alt="UTOOLS1596077559668.png" title="UTOOLS1596077559668.png" /> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.slim.js"></script> <script type="text/javascript"> $(function () { $(".js-lazy").each(function (i) { var src = $(this).data("src"); $(this).attr("src",src) }) }) </script> ``` ## 原生图片懒加载 方式一 ``` var bodyScrollHeight = document.body.scrollTop;// body滚动高度 var windowHeight = window.innerHeight;// 视窗高度 var imgs = document.getElementsByClassName('lazyloadimg'); for (var i =0; i < imgs.length; i++) { var imgHeight = imgs[i].offsetTop;// 图片距离顶部高度 if (imgHeight < windowHeight + bodyScrollHeight) { imgs[i].src = imgs[i].getAttribute('data-src'); img[i].className = img[i].className.replace('lazyloadimg','') } } } ``` 方式二 ``` // <img src="default.png" data-src="https://xxxx/real.png"> function isVisible(el) { const position = el.getBoundingClientRect() const windowHeight = document.documentElement.clientHeight // 顶部边缘可见 const topVisible = position.top > 0 && position.top < windowHeight; // 底部边缘可见 const bottomVisible = position.bottom < windowHeight && position.bottom > 0; return topVisible || bottomVisible; } function throttle(func, ms = 1000) { let canRun = true return function (...args) { if (!canRun) return canRun = false setTimeout(() => { func.apply(this, args) canRun = true }, ms) } } function imageLazyLoad() { const images = document.querySelectorAll('img') for (let img of images) { const realSrc = img.dataset.src if (!realSrc) continue if (isVisible(img)) { img.src = realSrc img.dataset.src = '' } } } // 测试 window.addEventListener('load', imageLazyLoad) window.addEventListener('scroll', imageLazyLoad) // or window.addEventListener('scroll', throttle(imageLazyLoad, 1000)) ```