绑定滚动事件on-scroll
<ion-content on-scroll="scroll()"
// 可见区域的高度
var windowHeight = $(window).height();
$scope.scroll = function(){
lazyLoadImage();
}
// repeat渲染结束后再lazyload
$scope.$on('ngRepeatFinished', function(){
lazyLoadImage();
})
// lazyload的实现
function lazyLoadImage(){
var windowHeight = $(window).height();
imgCache = $('img.lazyload')
imgCache.each(function(index, el) {
if($(el).offset().top - windowHeight < -100){
var url = $(el).attr('data-url');
$(el).attr('src', url);
$(el).removeClass('lazyload');
$(el).addClass('animated fadeIn');
}
});
}
end-repeat指令代码
.directive('endRepeat', ['$timeout', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit('ngRepeatFinished');
});
}
}
}
}])
模板代码
<img data-url="{{produce.produce_image}}" class="lazyload" ng-repeat="produce in produces" end-repeat>
原理:将图片的src设置在data-url中,当随着页面滚动,图片进入可视区域时,将src设置为data-url的值