图片懒加载(lazyloading)

需用到jquery和lodash两个套件

步骤一
帮图片加入 lazyloadimg 这个class

步骤二
图片的html要这样写
<img src="放loading的样式图片或是不放都行" data-src="图片的路径" alt="" class="lazyloadimg">

步骤三
window.onscroll =_.throttle(watchscroll, 200);
function watchscroll(){
console.log('123');
var bodyScrollHeight = $(document).scrollTop();// body滚动高度
var windowHeight = window.innerHeight;// 视窗高度
var imgs = document.getElementsByClassName('lazyloadimg');
console.log(bodyScrollHeight);
for (var i =0; i < imgs.length; i++) {
var imgHeight = $(imgs[i])[0].offsetTop// 图片距离顶部高度
console.log(imgHeight);
if (imgHeight < windowHeight + bodyScrollHeight) {
imgs[i].src = imgs[i].getAttribute('data-src');
imgs[i].className = imgs[i].className.replace('lazyloadimg','')
}
}
}



留言

這個網誌中的熱門文章

jquery取得 input array 陣列

CI 使用ckeditor,ckfinder的替代品