标签:var clear 间隔 context tor rom listen 函数 dev
window.onload = function(){ var scrollTop = window.scrollY; var imgs = Array.from(document.querySelectorAll(‘img‘)); lazyLoad(); // 采用了节流函数 window.addEventListener(‘scroll‘,throttle(lazyLoad,500,1000)); function throttle(fun, delay, time) { var timeout, startTime = new Date(); return function() { var context = this, args = arguments, curTime = new Date(); clearTimeout(timeout); // 如果达到了规定的触发时间间隔,触发 handler console.log(curTime - startTime) if (curTime - startTime >= time) { fun(); startTime = curTime; // 没达到触发间隔,重新设定定时器 } else { timeout = setTimeout(fun, delay); } }; }; // 实际想绑定在 scroll 事件上的 handler // 需要访问到imgs , scroll function lazyLoad(){ scrollTop = window.scrollY; imgs.forEach((item,index)=>{ if( scrollTop===0 && item.dataset.src !== ‘‘ && item.offsetTop < window.innerHeight + scrollTop ){ // alert() item.setAttribute(‘src‘,item.dataset.src) item.setAttribute(‘data-src‘,‘‘) }else if( item.dataset.src !== ‘‘ && item.offsetTop < window.innerHeight + scrollTop && item.offsetTop > scrollTop ){ item.setAttribute(‘src‘,item.dataset.src) item.setAttribute(‘data-src‘,‘‘) } }) } }
标签:var clear 间隔 context tor rom listen 函数 dev
原文地址:https://www.cnblogs.com/xuziwen/p/12177792.html