首页 > 代码库 > 滚屏异步加载图片

滚屏异步加载图片

 

 

 

 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>

    <style>
    </style>
</head>
<body>
<div id="image">
</div>

<script src="js/jquery-1.11.3.js"></script>
<script src="js/jquery.js"></script>
<!--<script src="http://www.mamicode.com/js/jquery.lazyload.js"></script>-->
<script>

    (function($){
        //alert($.fn.scrollLoading);
        $.fn.scrollLoading = function(options) {
            var defaults = {
                attr: "data-url"
            };
            var params = $.extend(
                    {},
                    defaults,
                    options || {}
            );
            params.cache = [];
            //$(this) 指的是 调用者(‘.scrollLoading‘);
            //console.log($(this).attr(‘class‘));
            $(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") {
                                o.attr("src", url);
                            } else {
                                o.load(url);
                            }
                            data.obj = null;
                        }
                    }
                });
                return false;
            };

            loading();
            $(window).bind("scroll", loading);
        }
    })(jQuery);
</script>

<script>
    var imgArr = "";
    for (var i = 1; i <= 25; i++) {
        if (i <= 25) {//因上传到17素材超过规定大小,不得不将过多的图片略去,为了达到更好的效果,可以自行修改此循环代码,并且增加其余图片,体验异步加载
            imgArr += <img class="scrollLoading" data-url="image/ + i + .jpg" src="http://www.mamicode.com/image/grey.gif" />;
        } else {
            imgArr += <img class="scrollLoading" data-url="image/13.jpg" src="http://www.mamicode.com/image/grey.gif" />;  //超过26张后显示的图片
        }
    }
    $("#image").append(imgArr);
    $("img").load(function () {
        //图片默认隐藏
        $(this).hide();
        //使用fadeIn特效
        $(this).stop().fadeIn("5000");
    });
//    // 异步加载图片,实现逐屏加载图片
    $(".scrollLoading").scrollLoading();

</script>
</body>
</html>

 

滚屏异步加载图片