经常看到些网站滚动时自动加载图片,这样做的好处是,不必一次性加载完所有数据,就可以浏览内容。
查找了些相关资,现作下整理:
1、jQuery滚动加载插件scrollLoading,将其封装做成插件:
jquery.scrollLoading.js
(function($) {
$.fn.scrollLoading = function(options) {
var defaults = {
attr: "data-url"
};
var params = $.extend({}, defaults, options || {});
params.cache = [];
$(this).each(function() {
var node = this.nodeName.toLowerCase(), url = $(this).attr(params["attr"]);
if (!url) { return; }
//重组
var data = {
obj: $(this),
tag: node,
url: url
};
params.cache.push(data);
});
//动态显示数据
var loading = function() {
var st = $(window).scrollTop(), sth = st + $(window).height();
$.each(params.cache, function(i, data) {
var o = data.obj, tag = data.tag, url = data.url;
if (o) {
post = o.position().top; posb = post + o.height();
if ((post > st && post < sth) || (posb > st && posb < sth)) {
//在浏览器窗口内
if (tag === "img") {
//图片,改变src
o.attr("src", url);
} else {
o.load(url);
}
data.obj = null;
}
}
});
return false;
};
//事件触发
//加载完毕即执行
loading();
//滚动执行
$(window).bind("scroll", loading);
};
})(jQuery);
2、scrollLoading使用
<script type="text/javascript" src="../ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript" src="../js/jquery.scrollLoading.js"></script>
<script>
$(function() {
$(".scrollLoading").scrollLoading();
});
</script>
3、HTML中加载图片代码
<div id="zxxMainCon" class="zxx_main_con">
<script>
var tempHTML = "";
for (var i=1; i<=30; i+=1) {
if (i == 6) {
tempHTML += '<div class="zxx_test_list scrollLoading" data-url="loaded.html"><div style="padding:100px 0; text-align:center;"><img src="http://www.zhangxinxu.com/study/image/loading.gif" style="margin:0 8px -8px 0;" />加载中...</div></div>';
} else {
tempHTML += '<div class="zxx_test_list tc"><img class="scrollLoading" data-url="http://image.zhangxinxu.com/image/study/head/s180/'+i+'.jpeg" src="http://www.zhangxinxu.com/study/image/pixel.gif" width="180" height="180" style="background:url(http://www.zhangxinxu.com/study/image/loading.gif) no-repeat center;" /><br />图片'+i+'(新浪微博提供)</div>';
}
}
document.getElementById("zxxMainCon").innerHTML = tempHTML;
</script>
</div>
1477

被折叠的 条评论
为什么被折叠?



