/*! * 2012-01-13 v1.1 偏移值计算修改 position → offset * 2012-09-25 v1.2 增加滚动容器参数, 回调参数 * 2015-11-17 v1.3 只对显示元素进行处理 */ (function($) { $.fn.scrollLoading = function(options) { var defaults = { attr: "data-url", container: $(window), callback: $.noop }; var params = $.extend({}, defaults, options || {}); params.cache = []; $(this).each(function() { var node = this.nodeName.toLowerCase(), url = $(this).attr(params["attr"]); //重组 var data = { obj: $(this), tag: node, url: url }; params.cache.push(data); }); var callback = function(call) { if ($.isFunction(params.callback)) { params.callback.call(call.get(0)); } }; //动态显示数据 var loading = function() { var contHeight = params.container.height(); if ($(window).get(0) === window) { contop = $(window).scrollTop(); } else { contop = params.container.offset().top; } $.each(params.cache, function(i, data) { var o = data.obj, tag = data.tag, url = data.url, post, posb; if (o) { post = o.offset().top - contop, post + o.height(); if (o.is(‘:visible‘) && (post >= 0 && post < contHeight) || (posb > 0 && posb <= contHeight)) { if (url) { //在浏览器窗口内 if (tag === "img") { //图片,改变src callback(o.attr("src", url)); } else { o.load(url, {}, function() { callback(o); }); } } else { // 无地址,直接触发回调 callback(o); } data.obj = null; } } }); }; //事件触发 //加载完毕即执行 loading(); //滚动执行 params.container.bind("scroll", loading); }; })(jQuery); //实例
<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="/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="//image.zhangxinxu.com/image/study/head/s180/‘+i+‘.jpeg" src="//s1.xiaomishu.com/b/img/pixel.gif" width="180" height="180" style="background:url(/study/image/loading.gif) no-repeat center;" /><br />图片‘+i+‘(新浪微博提供)</div>‘; } } tempHTML += ‘<div class="zxx_test_list tc"><h6>下面藏了一张图片,<a href="javascript:" id="zxxClickBtn">点击显示</a></h6>\ <div id="zxxShow" style="display:none;">\ <img class="scrollLoading" width="256" height="191" data-url="//image.zhangxinxu.com/image/study/s/s256/mm1.jpg" />\ </div></div>‘; document.getElementById("zxxMainCon").innerHTML = tempHTML;</script>
<script> $(function() { $(".scrollLoading").scrollLoading({ container: $("#zxxMainCon"), callback: function() { this.style.border = "3px solid #a0b3d6"; } }); //$(".scrollLoading").scrollLoading(); });</script>
原文地址:https://www.cnblogs.com/xieyongbin/p/10324313.html
时间: 2024-10-07 18:38:05