最近研究了京東商城用jQuery的實現如下:
就是默認地址賦給img標簽的src2屬性,顯示時賦給src屬性值。
function lazyload(option) {
var settings = {
defObj: null,
defHeight: 0
};
settings = $.extend(settings, option || {});
var defHeight = settings.defHeight;
var defObj = (typeof settings.defObj == "object") ? settings.defObj.find("img") : $(settings.defObj).find("img");
var pageTop = function() {
return document.documentElement.clientHeight + Math.max(document.documentElement.scrollTop, document.body.scrollTop) - settings.defHeight;
};
var imgLoad = function() {
defObj.each(function() {
if ($(this).offset().top <= pageTop()) {
var src2 = $(this).attr("src2");
//已顯示的不用再顯示
if (src2) {
//顯示後,去掉src2屬性
$(this).attr("src", src2).removeAttr("src2");
}
}
});
};
imgLoad();
$(window).bind("scroll", function() {
imgLoad();
});
}
lazyload({
defObj:".w1"
});