1.先定義須要懶加載的樣式;前端
class="lazyload"this
2.設置初始透明度爲0.1;圖片
.lazyload{ip
filter: Alpha(opacity=10); -moz-opacity:0.1; opacity:0.1;ci
}element
3.把真正須要加載的真實地址放在data-src屬性中;開發
src="懶加載圖片.png" data-src="真實圖片";get
4.it
前端開發周大偉同窗JavaScript代碼編寫:io
// 懶加載
function lazyLoad(){
if (window.addEventListener){
window.addEventListener("load",loading);
window.addEventListener("click",loading);
window.addEventListener("scroll",function(){
setTimeout(loading,100);
});
} else if (window.attachEvent) {
window.attachEvent("onload",loading);
window.attachEvent("onclick",loading);
window.attachEvent("onscroll",function(){
setTimeout(loading,100);
});
}
}
function loading(){
var lazyload=document.getElementsByClassName("lazyload");
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;
}
}
}
//獲取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; };