/********************************************
* 懒加载图片数据
* 作者: wangwenqing403@163.com
* 时间: 2012-11-22
********************************************/
var Lazyload = function (obj) {
this.content = $(obj);
this.min = $(document).scrollTop();
this.max = $(document).scrollTop() + $(window).height();
this.fnLoad = (function (object,handler) {
return function () {
return handler.apply(object, arguments);
};
})(this, this.load);
this.load();
$(window).bind('scroll', this.fnLoad)
.bind('resize', this.fnLoad);
};
Lazyload.prototype = {
load: function () {
var sT = $(document).scrollTop(), //滚动条高度
wH = $(window).height(), //窗口高度
cH = wH + sT,
oLoad, top, bottom;
if (this.check(sT, cH, wH)) return;
this.img = $('img[data-img][lazy!=1]', this.content);
if (this.loaded(1).length != this.img.length) {
oLoad = this.loaded(0);
$.each(oLoad, function () {
top = $(this).offset().top;
bottom = top + $(this).outerHeight();
if ((top > sT && top < cH) || (bottom > sT && bottom < cH)) {
$(this).attr('lazy', 1)
.attr('src', $(this).attr('data-img'));
}
});
}
else this.endLoad();
},
loaded: function (status) {
var arr = [], temp;
status = !!status;
this.img.each(function () {
temp = !!$(this).attr('lazy');
if (status) {
temp && arr.push($(this));
}
else {
temp || arr.push($(this));
}
});
return arr;
},
check: function (t, h, wh) {
if (t > this.min && h < this.max) return true;
if (t < this.min && Math.abs(this.min - t) <= wh) this.min = t;
if (h > this.max && Math.abs(this.max - h) <= wh) this.max = h;
return false;
},
endLoad: function () {
$(window).unbind('scroll', this.fnLoad)
.unbind('resize', this.fnLoad);
}
};
简单的懒加载图片数据
最新推荐文章于 2024-11-08 14:57:18 发布