【js】瀑布流、向下滑动、ajax先加载完图片再排列

最近的项目中经常会碰到以瀑布流方式布局的问题。

先从网上找了个瀑布流的图片排列插件。这里暂且用 jquery.masonry.js

废话不多说、直接上源码

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>masonry</title>
    <style>
        * {
            box-sizing: border-box; /* h5 */
            -moz-box-sizing: border-box; /* Firefox */
            -webkit-box-sizing: border-box; /* Safari */
            word-break:break-all;
        }

        html, body {
            margin: 0;
            padding: 0;
        }

        img {
            border: 0;
            display: block;
        }

        ul, ol,p,h1, h2, h3, h4, h5, h6{
            margin: 0;
            list-style: none;
            padding: 0;
        }

        .container{
            position: relative;
            width: 890px;
            clear: both;
            display: block;
            margin: 0 auto;
        }
        .photoList{
            margin-right: -15px;
        }
        .photoList li{
            width: 285px;
            float: left;
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
            margin-right: 15px;
            margin-bottom: 15px;
            min-height: 100px;
        }
        .photoList li>img{
            width: 100%;
        }
    </style>
</head>

<body>
<div class="container">
    <p style="line-height: 55px">与大家一起分享您的美妙旅程~ 可将旅程照片发送到帝国假日照片墙信箱 [email protected]</p>
    <ul class="photoList">

    </ul>
</div>

<div class="photoPop" style="display: none">
    <img id="bigPhoto" src="" alt="">
</div>

</body>


<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="js/jquery.masonry.min.js"></script>  <!--瀑布流插件-->
<script type="text/javascript" src="layer/layer.js"></script>       <!--弹出层插件-->
<script>
    //ajax请求第几页的数据
    var noPage = 1;
    //是否请求出AJAX的“开关”;
    var onOff = true;
    //瀑布流全局变量
    var $grid;

    $(function () {
        //瀑布流初始化
         $('.photoList').imagesLoaded(function() {
            $grid = $('.photoList').masonry({
                gutterWidth: 0,
                itemSelector: '.photoList li',
                isAnimated: true
            });
        });
        //向下滑动加载更多
        $(window).scroll(function(){
            var scrollTop = $(this).scrollTop();
            var scrollHeight = $(document).height();
            var windowHeight = $(this).height();
            if(scrollTop + windowHeight >= scrollHeight){
                if (onOff){
                    onOff=false;
                    photoList();
                }

            }
        });
        //获取ajax数据
        photoList();
    });


    function photoList() {
        $.ajax({
            type: 'GET',
            url: 'http://beyondestinations.com/api/api1020?resulttype=jsonp',
            data:{
                CurrentPage:noPage,
                PageSize:30
            },
            dataType:'jsonp',
            success:function(json) {
                var list=json.DataList;
                var str="";
                if(list.length>0){
                    var index = 0;
                    for(i=0;i<list.length;i++){
                        if (list[i].LogoUrl){
                            str+='<li><img onclick="photoShow(this)" src="'+list[i].LogoUrl+'" alt=""></li>';

                            //这里很重要!!!  一定要判断所有图片都加载完后、在进行瀑布流初始化!!
                            var img = new Image();
                            img.src = list[i].LogoUrl;
                            img.onload = function () {
                                index++;
                                if (index == list.length) {
                                    $grid.masonry("reload");
                                }
                            }
                         }


                    }
                    var $items = $(str);
                    // append items to grid
                    $grid.append( $items );
               
                    noPage++;

                    onOff=true;
                }else {
                    onOff=false;
                }
            }
        })


    }

    //视需求而定是否需要,点击图片显示原图
    function photoShow(obj) {

        var _w = parseInt($(window).width());//获取浏览器的宽度
        var img = $(obj);
        var realWidth;//真实的宽度
        var realHeight;//真实的高度
        var rsrc = $(img).attr("src");
        //这里做下说明,$("<img/>")这里是创建一个临时的img标签,类似js创建一个new Image()对象!
        $("<img/>").attr("src", rsrc).load(function() {
            /*
             如果要获取图片的真实的宽度和高度有三点必须注意
             1、需要创建一个image对象:如这里的$("<img/>")
             2、指定图片的src路径
             3、一定要在图片加载完成后执行如.load()函数里执行
             */
            realWidth = this.width;
            realHeight = this.height;

            //如果真实的宽度大于浏览器的宽度就按照100%显示
            $("#bigPhoto").attr("src",rsrc);
            if(realWidth>=_w){
                $("#bigPhoto").css("width","100%").css("height","auto");
            }
            else{//如果小于浏览器的宽度按照原尺寸显示
                $("#bigPhoto").css("width",realWidth+'px').css("height",realHeight+'px');
            }
            //弹出层插件 layer
            layer.open({
                type: 1,
                title: false,
                closeBtn: 0,
                shift: 2,
                shade:0.7,
                area: [''+realWidth+'px', ''+realHeight+'px'],
                // scrollbar: false,
                shadeClose: true, //开启遮罩关闭
                content: $(".photoPop")
            });

        });

    }
</script>
</html>

自己改下ajax  url,改下插件的路径,就可以用了。注释相信也写的很详细了,还有问题的朋友欢迎留言互相探讨学习。


补充一下,判断所有图片加载完毕还有另外一个方法,有兴趣的可以了解下。

  
    isImgLoad(function () {
        $grid.masonry("reload");
    });

    var t_img; // 定时器
    var isLoad = true; // 控制变量

    // 判断图片加载的函数
    function isImgLoad(callback){
        // 注意我的图片类名都是photoList,因为我只需要处理photoList。其它图片可以不管。
        // 查找所有封面图,迭代处理
        $('.photoList img').each(function(){
            // 找到为0就将isLoad设为false,并退出each
            if(this.height === 0){
                isLoad = false;
                return false;
            }
        });
        // 为true,没有发现为0的。加载完毕
        if(isLoad){
            clearTimeout(t_img); // 清除定时器
            // 回调函数
            callback();
            // 为false,因为找到了没有加载完成的图,将调用定时器递归
        }else{
            isLoad = true;
            t_img = setTimeout(function(){
                isImgLoad(callback); // 递归扫描
            },500); // 我这里设置的是500毫秒就扫描一次,可以自己调整
        }
    }



猜你喜欢

转载自blog.csdn.net/unionz/article/details/80547999