你的位置:首页 > Java教程

[Java教程]picLazyLoad 图片延时加载,包含背景图片


 1 /** 2  * picLazyLoad 图片延时加载,包含背景图片 3  * $(img).picLazyLoad({...}) 4  * data-original 预加载图片地址 5  * alon 6 */ 7 ;(function($){ 8   $.fn.imgLazyLoad = function(settings){ 9     var $this = $(this),10       _winScrollTop = 0,11       _winHeight = $(window).height();12     settings = $.extend({13       threshold: 0, // 提前高度加载14       placeholder: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC',15       callback:function(){}16     }, settings||{});17     // 执行懒加载图片18     lazyLoadPic();19     // 滚动触发换图20     $(window).on('scroll',function(){21       _winScrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;22       lazyLoadPic();23     });24     // 懒加载图片25     function lazyLoadPic(){26       $this.each(function(){27         var $self = $(this);28         if($self.is('img')){29           if($self.attr('data-original')){30             var _offsetTop = $self.offset().top;31             if((_offsetTop - settings.threshold) <= (_winHeight + _winScrollTop)){32               $self.attr('src',$self.attr('data-original'));33               $self.removeAttr('data-original');34               $self.removeClass('loadH');35               settings.callback($self);36             }37           }38         }else{39           if($self.attr('data-original')){// 默认占位图片40             if($self.css('background-image') == 'none'){41               $self.css('background-image','url('+settings.placeholder+')');42             }43             var _offsetTop = $self.offset().top;44             if((_offsetTop - settings.threshold) <= (_winHeight + _winScrollTop)){45               $self.css('background-image','url('+$self.attr('data-original')+')');46               $self.removeAttr('data-original');47               settings.callback($self);48             }49           }50         }51       });52     }53   }54 })(Zepto);

调用

1 $('img').imgLazyLoad({callback:function(data){2 3 })