Open conan1992 opened 4 years ago
节流方法
//节流: 在一定时间内触发一次 function throttle(fn, delay){ var timestamp = 0; return function(){ var now = +new Date(); if(now -timestamp < delay) return; fn(); timestamp = now; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>呵呵</title> <style> ul li { min-height: 300px; } img { width: 500px;} </style> </head> <body> <ul> <li> <img src="./default.jpg" data-src="http://shp.qpic.cn/ishow/2735070311/1593748762_84828260_23096_sProdImgNo_7.jpg/0"> </li> <li> <img src="./default.jpg" data-src="http://shp.qpic.cn/ishow/2735070311/1593748762_84828260_23096_sProdImgNo_7.jpg/0"> </li> <li> <img src="./default.jpg" data-src="http://shp.qpic.cn/ishow/2735070311/1593748762_84828260_23096_sProdImgNo_7.jpg/0"> </li> <li> <img src="./default.jpg" data-src="http://shp.qpic.cn/ishow/2735070311/1593748762_84828260_23096_sProdImgNo_7.jpg/0"> </li> <li> <img src="./default.jpg" data-src="http://shp.qpic.cn/ishow/2735070311/1593748762_84828260_23096_sProdImgNo_7.jpg/0"> </li> <li> <img src="./default.jpg" data-src="http://shp.qpic.cn/ishow/2735070311/1593748762_84828260_23096_sProdImgNo_7.jpg/0"> </li> <li> <img src="./default.jpg" data-src="http://shp.qpic.cn/ishow/2735070311/1593748762_84828260_23096_sProdImgNo_7.jpg/0"> </li> </ul> </body> <script> //节流: 在一定时间内触发一次 function throttle(fn, delay){ var timestamp = 0; return function(){ var now = +new Date(); if(now -timestamp < delay) return; fn(); timestamp = now; } } var imgs = document.querySelectorAll("img"); var count = 0; console.log(imgs, imgs[0].getBoundingClientRect()) function lazyLoad(){ console.log("lazyloading...") var viewHeight = document.documentElement.clientHeight; var scrollTop = document.documentElement.scrollTop || document.body.scrollTop for(var i = count; i<imgs.length;i++){ if(imgs[i].offsetTop<viewHeight + scrollTop){ console.log(i) imgs[i].src = imgs[i].getAttribute("data-src"); count++; } } } lazyLoad(); window.addEventListener("scroll", throttle(lazyLoad, 200)) </script> </html>
if(imgs[i].getBoundingClientRect().top<viewHeight){ console.log(i) imgs[i].src = imgs[i].getAttribute("data-src"); count++; }
var imgs = document.querySelectorAll("img"); var count = 0; console.log(imgs) var observer = new IntersectionObserver(function(entries){ for(var i = 0; i<entries.length;i++){ if(entries[i].isIntersecting){ entries[i].target.src = entries[i].target.getAttribute("data-src"); observer.unobserve( imgs[i] ) } } }) imgs.forEach(item => { observer.observe( item ) })
clientHeight、scrollTop 和 offsetTop
节流方法
getBoundingClientRect
参考