瀑布流 结合 懒加载 操作实例

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0,user-scalable=no" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <title></title>
    <script src="../Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script src="../Scripts/Jquerymobile/lazyload/jquery.lazyload.js" type="text/javascript"></script>
    <style type="text/css">
        *
        {
            margin: 0;
            padding: 0;
            text-decoration: none;
            list-style-type: none;
            font-family: "Microsoft YaHei" ,sans-serif,serif;
            font-size: 1em;
        }
        body, div
        {
            margin: 0;
            padding: 0;
        }
        img
        {
            border: 0;
        }
        
        .clearFloat:after
        {
            content: ".";
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }
        .noDisplay
        {
            display: none;
        }
        .position_r
        {
            position: relative;
        }
        .item_1
        {
            width: 100%;
            float: left;
            overflow: hidden;
        }
        .item_1_s
        {
            background-color: #FFFFFF;
            border: 5px solid #fff;
            width: 91%;
            margin: 5px auto;
            font-size: 1em;
            box-shadow: 1px 1px 1px #aaa;
        }
        .item_1 img
        {
            width: 100%;
        }
        .item_1 .item_title
        {
            color: rgb(43,45,44);
            width: 100%;
        }
        .item_1 .item_title a
        {
            color: rgb(43,45,44);
        }
        .item_1 .item_price
        {
            zoom: 1;
        }
        .item_1 .item_price span
        {
            display: inline-block;
        }
        .item_1 .item_price .price_1
        {
            color: rgb(183,18,21);
        }
        .item_1 .item_price .price_2
        {
            margin-left: 10px;
            font-size: 0.7em;
            text-decoration: line-through;
            color: rgb(146, 146, 146);
        }
        .item_fx
        {
        }
        .info
        {
            font-size: 1.3em;
            text-align: left;
        }
        .zk
        {
            display: block;
            padding: 2px 5px;
            font-size: 0.6em;
            background-color: #BD0000;
            color: #FFFFFF;
            position: absolute;
            top: 0;
            right: 0;
        }
        .s1
        {
            font-size: 0.7em;
        }
        .contentBg
        {
            background-color: #eaecef;
        }
        .dataInfo
        {
            color: #B5AD7E;
            white-space: nowrap;
            overflow: hidden;
        }
        .dataInfo div
        {
            display: inline-block;
            clear: none;
            height: 35px;
        }
        .weekInfo
        {
            width: 60px;
            font-size: 1em;
            white-space: normal;
        }
        .weekInfo span
        {
            width: 100%;
            display: inline-block;
        }
    </style>
    <script type="text/javascript">
        /**
        ************************************************************
        **** 瀑布流
        ************************************************************
        */
        (function ($) {
            var 
            //参数
   setting = {
       column_width: 150, //列宽
       column_className: 'waterfall_column', //列的类名
       column_space: 10, //列间距
       cell_selector: '.cell', //要排列的砖块的选择器,context为整个外部容器
       img_selector: 'img', //要加载的图片的选择器
       auto_imgHeight: true, //是否需要自动计算图片的高度
       fadein: true, //是否渐显载入
       fadein_speed: 600, //渐显速率,单位毫秒
       insert_type: 1, //单元格插入方式,1为插入最短那列,2为按序轮流插入
       getResource: function (index) { }  //获取动态资源函数,必须返回一个砖块元素集合,传入参数为加载的次数
   },
            //
   waterfall = $.waterfall = {}, //对外信息对象
   $container = null; //容器
            waterfall.load_index = 1, //加载次数
   $.fn.extend({
       waterfall: function (opt) {
           opt = opt || {};
           setting = $.extend(setting, opt);
           $container = waterfall.$container = $(this);
           waterfall.$columns = creatColumn();
           render($(this).find(setting.cell_selector).detach(), false); //重排已存在元素时强制不渐显
           waterfall._scrollTimer2 = null;
           $(window).bind('scroll', function () {
               clearTimeout(waterfall._scrollTimer2);
               waterfall._scrollTimer2 = setTimeout(onScroll, 300);
           });
           waterfall._scrollTimer3 = null;
           $(window).bind('resize', function () {
               clearTimeout(waterfall._scrollTimer3);
               waterfall._scrollTimer3 = setTimeout(onResize, 300);
           });
       }
   });
            function creatColumn() {//创建列
                waterfall.column_num = calculateColumns(); //列数
                //循环创建列
                var html = '';
                for (var i = 0; i < waterfall.column_num; i++) {
                    html += '<div class="' + setting.column_className + '" style="width:' + setting.column_width + 'px; display:inline-block; *display:inline;zoom:1; margin-left:' + setting.column_space / 2 + 'px;margin-right:' + setting.column_space / 2 + 'px; vertical-align:top; overflow:hidden"></div>';
                }
                $container.prepend(html); //插入列
                return $('.' + setting.column_className, $container); //列集合
            }
            function calculateColumns() {//计算需要的列数
                var num = Math.floor(($container.innerWidth()) / (setting.column_width + setting.column_space));
                if (num < 1) { num = 1; } //保证至少有一列
                return num;
            }
            function render(elements, fadein) {//渲染元素
                if (!$(elements).length) return; //没有元素
                var $columns = waterfall.$columns;
                $(elements).each(function (i) {
                    if (!setting.auto_imgHeight || setting.insert_type == 2) {//如果给出了图片高度,或者是按顺序插入,则不必等图片加载完就能计算列的高度了
                        if (setting.insert_type == 1) {
                            insert($(elements).eq(i), setting.fadein && fadein); //插入元素
                        } else if (setting.insert_type == 2) {
                            insert2($(elements).eq(i), i, setting.fadein && fadein); //插入元素  
                        }
                        return true; //continue
                    }
                    if ($(this)[0].nodeName.toLowerCase() == 'img' || $(this).find(setting.img_selector).length > 0) {//本身是图片或含有图片
                        var image = new Image;
                        var src = $(this)[0].nodeName.toLowerCase() == 'img' ? $(this).attr('src') : $(this).find(setting.img_selector).attr('src');
                        image.onload = function () {//图片加载后才能自动计算出尺寸
                            image.onreadystatechange = null;
                            if (setting.insert_type == 1) {
                                insert($(elements).eq(i), setting.fadein && fadein); //插入元素
                            } else if (setting.insert_type == 2) {
                                insert2($(elements).eq(i), i, setting.fadein && fadein); //插入元素  
                            }
                            image = null;
                        }
                        image.onreadystatechange = function () {//处理IE等浏览器的缓存问题:图片缓存后不会再触发onload事件
                            if (image.readyState == "complete") {
                                image.onload = null;
                                if (setting.insert_type == 1) {
                                    insert($(elements).eq(i), setting.fadein && fadein); //插入元素
                                } else if (setting.insert_type == 2) {
                                    insert2($(elements).eq(i), i, setting.fadein && fadein); //插入元素  
                                }
                                image = null;
                            }
                        }
                        image.src = src;
                    } else {//不用考虑图片加载
                        if (setting.insert_type == 1) {
                            insert($(elements).eq(i), setting.fadein && fadein); //插入元素
                        } else if (setting.insert_type == 2) {
                            insert2($(elements).eq(i), i, setting.fadein && fadein); //插入元素  
                        }
                    }
                });


            }
            function public_render(elems) {//ajax得到元素的渲染接口
                render(elems, true);
            }
            function insert($element, fadein) {//把元素插入最短列
                if (fadein) {//渐显
                    $element.css('opacity', 0).appendTo(waterfall.$columns.eq(calculateLowest())).fadeTo(setting.fadein_speed, 1);
                } else {//不渐显
                    $element.appendTo(waterfall.$columns.eq(calculateLowest()));
                }
                $("img.lazy").lazyload({});
            }
            function insert2($element, i, fadein) {//按序轮流插入元素
                if (fadein) {//渐显
                    $element.css('opacity', 0).appendTo(waterfall.$columns.eq(i % waterfall.column_num)).fadeTo(setting.fadein_speed, 1);
                } else {//不渐显
                    $element.appendTo(waterfall.$columns.eq(i % waterfall.column_num));
                }
                $("img.lazy").lazyload({});
            }
            function calculateLowest() {//计算最短的那列的索引
                var min = waterfall.$columns.eq(0).outerHeight(), min_key = 0;
                waterfall.$columns.each(function (i) {
                    if ($(this).outerHeight() < min) {
                        min = $(this).outerHeight();
                        min_key = i;
                    }
                });
                return min_key;
            }
            function getElements() {//获取资源
                $.waterfall.load_index++;
                return setting.getResource($.waterfall.load_index, public_render);
            }
            waterfall._scrollTimer = null; //延迟滚动加载计时器
            function onScroll() {//滚动加载
                clearTimeout(waterfall._scrollTimer);
                waterfall._scrollTimer = setTimeout(function () {
                    var $lowest_column = waterfall.$columns.eq(calculateLowest()); //最短列
                    var bottom = $lowest_column.offset().top + $lowest_column.outerHeight(); //最短列底部距离浏览器窗口顶部的距离
                    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop || 0; //滚动条距离
                    // alert('scrollTop===='+scrollTop);
                    // alert('bottom===='+bottom);
                    var windowHeight = document.body.clientHeight || document.documentElement.clientHeight || 0; //窗口高度
                    //alert('windowHeight===='+windowHeight);
                    //alert('ccc===='+(bottom - windowHeight));

                    if (scrollTop >= bottom - windowHeight) {
                        render(getElements(), true);
                    }
                    if (scrollTop <= 0) {
                        $("#DivLoading").fadeIn(2000);
                        //setTimeout('jumpurl()', 3000);
                        jumpurl();
                    }

                }, 100);
            }
            function onResize() {//窗口缩放时重新排列
                if (calculateColumns() == waterfall.column_num) return; //列数未改变,不需要重排
                var $cells = waterfall.$container.find(setting.cell_selector);
                waterfall.$columns.remove();
                waterfall.$columns = creatColumn();
                render($cells, false); //重排已有元素时强制不渐显
            }
        })(jQuery);
    </script>
</head>
<body style="text-align: center;">
    <div id="DivLoading">
        &nbsp;&nbsp;&nbsp;&nbsp;<img alt="" style="font-size: 1.2em; font-family: 微软雅黑;"
            src="../Scripts/Jquerymobile/ref.jpg">正在加载...
    </div>
    <div id="container" style="width: 100%; margin: 0 auto; overflow: hidden;">
        @{
            if (_productList != null)
            {
                foreach (ProductInfoCDTO _product in _productList)
                {
            <div class="cell">
                <div class="item_1" id="@(_product.ProductId)">
                    <div class="item_1_s">
                        <div class="position_r">
                            <img class="lazy" src="../Scripts/Jquerymobile/lazyload/grey.gif" data-original="@(_product.ImgUrl)" alt="" onclick="GoShoping('@(_product.ProductId)','@(_product.AdId)')" />
                            @{
                                string tempIntensity = string.Empty;
                                if (_product.Intensity != 10)
                                {
                                    tempIntensity = "<div class=\"zk\"> " + _product.Intensity + "折</div>";
                                }
                                else
                                {
                                    tempIntensity = "&nbsp;";
                                }
                            }
                            @(new HtmlString(tempIntensity))
                        </div>
                        <div class="info">
                            <div class="item_title">
                                @(_product.ProductName)</div>
                            <div class="item_price">
                                <span class="price_1">¥@(_product.ProductPrice)</span><span class="price_2">¥@(_product.Price)</span></div>
                            <div class="item_fx">
                                @{
                                     string tempRebate = string.Empty;
                                     if (_product.Rebate > 0)
                                     {
                                         tempRebate = "<div class=\"s1\">送金币" + _product.Rebate + "</div>";
                                     }
                                     else
                                     {
                                         tempRebate = "&nbsp;";
                                     }
                                }
                                @(new HtmlString(tempRebate))</div>
                            <div class="clearFloat">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
                }
            }
        }
    </div>
    <div id="TailDiv" style="display: none;">
        已经到尾部了</div>
    <input type="hidden" id="hidIsAnnon" value="@(ViewBag.isAnnon)" />
    <input type="hidden" id="hidDeviceId" value="@(ViewBag.deviceId)" />
    <input type="hidden" id="hidUserId" value="@(ViewBag.userId)" />
    <input type="hidden" id="hidAppid" value="@(ViewBag.appid)" />
</body>
</html>
<script type="text/javascript">
    var template = '<div class="item_1" id="{Id}">'
                        + '<div class="item_1_s">'
                        + '<div class="position_r">'
                        + '<img src="{图片}" alt="" onclick="GoShoping(\'{PId}\',\'{AdId}\')"/>{折扣}'
                        + '</div><div class="info">'
                        + '<div class="item_title">{名称}</div>'
                        + '<div class="item_price"><span class="price_1">¥{折扣价}</span><span class="price_2">¥{原价}</span></div>'
                        + '<div class="item_fx">{送金币}</div>'
                        + '<div class="clearFloat"></div>'
                        + '</div></div>'
                        + '</div>';
    var opt = {
        getResource: function (index, render) {//index为已加载次数,render为渲染接口函数,接受一个dom集合或jquery对象作为参数。通过ajax等异步方法得到的数据可以传入该接口进行渲染,如 render(elem)
           // alert(index);
            var _html = '';
              var postdata = { appId: $("#hidAppid").val(),
                userId: $("#hidUserId").val(),
                deviceId: $("#hidDeviceId").val(),
                isAnnon: $("#hidIsAnnon").val(),
                pageIndex: index,
                pageSize: 6};
            $.ajax({
                async: false,
                type: "POST",
                dataType: "json",
                url: "/GoodsWall/TempGetGoods?r="+Math.random(),
                 data: postdata,
                success: function (data) {
                    if (data) {
                        for (var i = 0; i < data.length; i++) {
                            var str = template;
                            str = str.replace("{图片}", data[i].ImgUrl);
                            str = str.replace("{名称}", data[i].ProductName);
                            str = str.replace("{折扣价}", data[i].ProductPrice);
                            str = str.replace("{原价}", data[i].Price);
                            str = str.replace("{Id}", data[i].ProductId);
                            str = str.replace("{PId}", data[i].ProductId);
                            str = str.replace("{AdId}", data[i].AdId);
                            if (data[i].Intensity != 10) {
                                str = str.replace("{折扣}", '<div class="zk">' + data[i].Intensity + '折</div>');
                            } else {
                                str = str.replace("{折扣}", '');
                            }
                            if (data[i].Rebate > 0) {
                                str = str.replace("{送金币}", '<span class="s1">送金币' + data[i].Rebate + '</span>'); //
                            }
                            else {
                                str = str.replace("{送金币}", "");
                            }

                            _html += str;
                        }
                        if(_html=='')
                        {
                            $("#TailDiv").show();
                        }
                        else
                        {
                           $("#TailDiv").hide();  
                        }
                    }
                },
                error: function (err) {
                }
            });

            return $(_html);
        },
        auto_imgHeight: true,
        insert_type: 1
    }
    $('#container').waterfall(opt);
    $(function () {
        $("img.lazy").lazyload({
            load: function () {
                $('#container').waterfall(opt);
            }
        });

        $("#DivLoading").fadeOut(1000);
    });
    function jumpurl() {
        location.reload();
    }
    
    // 商品通道
    function GoShoping(goodsId, adid) {
        var code = "";
        var appId = getQueryString('appId');
        var userId = getQueryString('userId');
        var postData = { "adid": adid, "userID": userId, "goodsId": goodsId, "appId": appId };
        $.ajax({
            async: false,
            type: "POST",
            dataType: "json",
            url: "/GoodsWall/CreateCps",
            data: postData,
            success: function (data) {
                if (data) { code = data; }
            },
            error: function (err) {
            }
        });

        var url =  "@Jinher.AMP.ADM.UI.Models.CustomConfigHelper.GetCustomConfig("CommodityDetail")"
            + "?userId=" + userId
            + "&appId=" + appId
            + "&commodityId=" + goodsId
            + "&adId=" + adid
            + "&cpsid=" + code
            + "&SrcType=28"
            + "&SrcTagId=" + adid;
        window.location.href = url;
    }


    //获取URL某值
    function getQueryString(name) {
        var r;
        if (arguments.length > 1) {
            r = arguments[1].split('?')[1];
        } else {
            r = window.location.search.substr(1);
        }
        //    var r = str ? str.split('?')[1] : '' || window.location.search.substr(1);
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        r = r.match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }
</script>

 

posted on 2014-12-18 15:50  【波少】  阅读(690)  评论(0编辑  收藏  举报

导航