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(){ 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; };