<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>页面滚动图片加载</title>
<style>
body{text-align:center;}
.list{margin-bottom:40px;}
</style>
</head>
<body>
<div>
<div>
<div id="content"> <!--先将要显示的图片地址隐藏,不显示图片,待事件触发时,加载地址,显示图片-->
<script type="text/javascript">
var imgurl=[4,5,6,25,26];//从后台取到图片地址,下面src里是一个1px图片,相当于没有,style里是loading图片,可替代为其他的
var main = "";
for(var i = 0;i<imgurl.length;i++)
{
main += '<div class="list"><img class="scrollLoading" xSrc="'+imgurl[i]+'.jpg" src="http://images.cnblogs.com/cnblogs_com/Darren_code/302725/o_pixel.gif" width="200" height="250" style="background:url(http://images.cnblogs.com/cnblogs_com/Darren_code/302725/o_108.gif) no-repeat center;" /><br /></div>';
}
document.getElementById("content").innerHTML = main;//这里只能把所有要显示的图片地址加载进来,并没有马上显示图片,实际根据页面滚动来加载的
</script>
</div>
</div>
</div>
<script type="text/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();
</script>
</body>
</html>
延迟图片滚动加载
最新推荐文章于 2021-06-05 00:05:20 发布