一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

javascript实现真正图片异步加载功能

时间:2011-07-22 编辑:简简单单 来源:一聚教程网

在图片load成功后可以加入合适的显示效果(例子中木有体现,可以自己尝试,在网上找到很多源码,但是都是假的,就是实现不了我们想要的节省浏览器资源的代码,下面我经过自己修改以及参考高手的帮,实现了真正的可视区域加载图片的方法。实现网站 http://www.111com.net

JavaScript源码如下:

var scrollLoad = (function (options) {
var defaults = (arguments.length == 0) ? { src: 'xSrc', time: 300} : { src: options.src || 'xSrc', time: options.time ||300};
var camelize = function (s) {
return s.replace(/-(w)/g, function (strMatch, p1) {
return p1.toUpperCase();
});
};
this.getStyle = function (element, property) {
if (arguments.length != 2) return false;
var value = element.style[camelize(property)];
if (!value) {
if (document.defaultView && document.defaultView.getComputedStyle) {
var css教程 = document.defaultView.getComputedStyle(element, null);
value = css ? css.getPropertyValue(property) : null;
} else if (element.currentStyle) {
value = element.currentStyle[camelize(property)];
}
}
return value == 'auto' ? '' : value;
};
var _init = function () {
var offsetPage = window.pageYOffset ? window.pageYOffset : window.document.documentElement.scrollTop,
offsetWindow = offsetPage + Number(window.innerHeight ? window.innerHeight : document.documentElement.clientHeight),
docImg = document.images,
_len = docImg.length;
if (!_len) return false;
for (var i = 0; i < _len; i++) {
var attrSrc = docImg[i].getAttribute(defaults.src),
o = docImg[i], tag = o.nodeName.toLowerCase();
if (o) {
postPage = o.getBoundingClientRect().top + window.document.documentElement.scrollTop + window.document.body.scrollTop; postWindow = postPage + Number(this.getStyle(o, 'height').replace('px', ''));
if ((postPage > offsetPage && postPage < offsetWindow) || (postWindow > offsetPage && postWindow < offsetWindow)) {
if (tag === "img" && attrSrc !== null) {
o.setAttribute("src", attrSrc);
}
o = null;
}
}
};
window.onscroll = function () {
setTimeout(function () {
_init();
}, defaults.time);
}
};
return _init();
});
scrollLoad();


动态改为src的值

scrollLoad({
src:'userSrc', //字符串型
time: 100 //数字型
})

热门栏目