// 防抖 let lazy_timer; window.addEventListener('scroll', function () { if (lazy_timer !== null){ clearTimeout(lazy_timer) } lazy_timer = setTimeout(function () { load_lazy(); }, 100) }); // 必須在window.onload裏主動調用一次 load_lazy(); // 懶加載 function load_lazy() { $('.lazy-img:not([data-l])').each(function () { let y = this.getBoundingClientRect().top; if ((y+this.offsetHeight >= 0 && y <= document.body.clientHeight) || this.getAttribute('data-main') === 't') { this.src = this.getAttribute('data-s'); this.setAttribute('data-l', ''); } }); }
以上代碼很簡潔,主要就是三點javascript