web前端图片懒加载


(function(){
	var imgList=[];//懒加载图片组成的数组
	var timer;//计时器
	var offset=0;//偏移量
	function imgShow(el){//判断img是否出现在可视窗口
        var positions = el.getBoundingClientRect();
        return positions.top <= (document.documentElement.clientHeight || window.innerHeight) + parseInt(offset);
    };
	function imgLoading(el){//滚动监听
        var  els = document.querySelectorAll(el);
        imgList = Array.apply(null,els);
        window.addEventListener('scroll',function(){
        	clearTimeout(timer);
        	timer=setTimeout(function(){
        		for(var i = 0 ; i < imgList.length; i++){
		            if(imgShow(imgList[i])){
		                imgList[i].src = imgList[i].getAttribute('data-src');
		                imgList.splice(i,1);
		            }
		        }
        	},300);
        },false)
    };
    imgLoading('.imgLazyLoad');
})();


猜你喜欢

转载自blog.csdn.net/qq_25065257/article/details/78216329