简单的懒加载图片数据

        /********************************************
         * 懒加载图片数据
         * 作者: wangwenqing403@163.com
         * 时间:  2012-11-22
         ********************************************/
        var Lazyload = function (obj) {
            this.content = $(obj);
            this.min = $(document).scrollTop();
            this.max = $(document).scrollTop() + $(window).height();
            this.fnLoad = (function (object,handler) {
                return function () {
                    return handler.apply(object, arguments);
                };
            })(this, this.load);
            this.load();
            $(window).bind('scroll', this.fnLoad)
                     .bind('resize', this.fnLoad);
        };

        Lazyload.prototype = {
            load: function () {
                var sT = $(document).scrollTop(), //滚动条高度
                    wH = $(window).height(), //窗口高度
                    cH = wH + sT,
                    oLoad, top, bottom;

                if (this.check(sT, cH, wH)) return;

                this.img = $('img[data-img][lazy!=1]', this.content);
                if (this.loaded(1).length != this.img.length) {
                    oLoad = this.loaded(0);
                    $.each(oLoad, function () {
                        top = $(this).offset().top;
                        bottom = top + $(this).outerHeight();
                        if ((top > sT && top < cH) || (bottom > sT && bottom < cH)) {
                            $(this).attr('lazy', 1)
                                   .attr('src', $(this).attr('data-img'));
                        }
                    });

                }
                else this.endLoad();
            },
            loaded: function (status) {
                var arr = [], temp;
                status = !!status;
                this.img.each(function () {
                    temp = !!$(this).attr('lazy');
                    if (status) {
                        temp && arr.push($(this));
                    }
                    else {
                        temp || arr.push($(this));
                    }
                });
                return arr;
            },
            check: function (t, h, wh) {
                if (t > this.min && h < this.max) return true;
                if (t < this.min && Math.abs(this.min - t) <= wh) this.min = t;
                if (h > this.max && Math.abs(this.max - h) <= wh) this.max = h;
                return false;
            },
            endLoad: function () {
                $(window).unbind('scroll', this.fnLoad)
                         .unbind('resize', this.fnLoad);
            }
        };


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值