今天在用iscoll 插件做滚动效果的时候,要实现滚动过程中,图片的懒加载,网上搜了下,没有现成的。
自己尝试写代码后,成功实现。先将源代码贴出如下。
iScroll版本为5,移动端库为 zepto
//初始化iscroll
var myScroll = new IScroll('#wrap');
//绑定滚动停止事件
myScroll.on('scrollEnd',function(){
showImage();
});
//显示图片
function showImage(){
$.each($('.lazy'),function(i,el){
if(isNeedLoad(el)){
el.src = $(el).removeClass('lazy').data('src');
}
});
}
//是否需要加载图片
function isNeedLoad(el){
var coords = el.getBoundingClientRect();
return (coords.top < window.innerHeight && coords.bottom > window.innerHeight) || (coords.bottom > 0 && coords.top < 0) || (coords.top > 0 && coords.bottom < window.innerHeight);
}
//手动执行一次,将一开始需要展示的图片先显示出来
showImage();
HTML代码如下:
//black.gif是张1*1的空白图片 class="lazy" 为需要做懒加载效果载的图片
<img src="img/blank.gif" data-src="img/8.png" alt="" class="lazy"/>
CSS代码如下。
.h-content-body img{max-width: 100%;height:188px;display: block;margin:0.6rem auto;border-radius: 2px;transition:all .5s;opacity:1;}
.h-content-body img.lazy{opacity:.5;background: url(../img/bg-img.png) no-repeat center center;} .
//background为一张背景图,用于显示公司默认图片logo的图片,有没有都可以
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。