JS图片根据鼠标滚动延时加载的实例代码
作者:
这篇文章介绍了,JS图片根据鼠标滚动延时加载的实例代码,有需要的朋友可以参考一下
最近研究了京东商城用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"
});
就是默认地址赋给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"
});