1.先定义需要懒加载的样式;
class="lazyload"
2.设置初始透明度为0.1;
.lazyload{
filter: Alpha(opacity=10); -moz-opacity:0.1; opacity:0.1;
}
3.把真正需要加载的真实地址放在data-src属性中;
src="懒加载图片.png" data-src="真实图片";
4.
前端开发周大伟同学JavaScript代码编写:
function lazyload(){
var lazyload=document.getElementsByClassName("lazyload");
window.addEventlistener("scroll",function(){
setTimeout(function(){
for(var i=0;i<lazyload.length;i++){
var _this=lazyload[i];
var clientHeight=document.documentElement.clientHeight || document.body.clientHeight;
var scrollTop=document.documentElement.scrollTop || document.body.scrollTop;
if(clientHeight+scrollTop>=offsetTop(_this)){
_this.setAttribute("src",_this.getAttribute("data-src"));
_this.style.opacity="1";
}
}
},100);
});
}
//获取offsetTop和offsetLeft值的js代码(兼容)
function offsetTop( elements ){
var top = elements.offsetTop;
var parent = elements.offsetParent;
while( parent != null ){
top += parent.offsetTop;
parent = parent.offsetParent;
};
return top;
};
function offsetLeft( elements ){
var left = elements.offsetLeft;
var parent = elements.offsetParent;
while( parent != null ){
left += parent.offsetLeft;
parent = parent.offsetParent;
};
return parent;
};