瀑布流布局实现原理及举例

2016-10-13  本文已影响3208人  该帐号已被查封_才怪

一、实现原理

瀑布流布局由pinterest.com网站首创,它的原理是:先通过计算出一排能够容纳几列元素,然后寻找各列之中所有元素高度之和的最小者,并将新的元素添加到该列上,然后继续寻找所有列的各元素之和的最小者,继续添加至该列上,如此循环下去,直至所有元素均能够按要求排列为止;

二、举例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        div.item{
            position: absolute;
            width: 200px;
            margin: 10px;
            transition: all 1s;
        }
        div#content{
            position: relative;

        }
        .part1{
            background-color: yellow;
            height: 200px;
        }
        .part2{
            background-color: #006ac1;
            height: 400px;
        }
        .part3{
            background-color: blueviolet;
            height: 300px;
        }
    </style>
</head>
<body>
    <div id="content">
        <div class="item part1">1</div>
        <div class="item part2">2</div>
        <div class="item part3">3</div>
        <div class="item part1">4</div>
        <div class="item part1">5</div>
        <div class="item part2">6</div>
        <div class="item part2">7</div>
        <div class="item part3">8</div>
        <div class="item part1">9</div>
        <div class="item part2">10</div>
        <div class="item part2">11</div>
        <div class="item part2">12</div>
        <div class="item part3">13</div>
        <div class="item part3">14</div>
    </div>
    <script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
        
        function waterFall() {

       var widthNum=parseInt($(window).width()/$(".item").outerWidth(true)),
                allHeight=[];

        for (var i=0;i<widthNum;i++){
            allHeight.push(0)
        }

        $(".item").each(function () {
            var $cur=$(this),
                    indx=0,
             minAllHeight=allHeight[0];
            for (var j=0;j<allHeight.length;j++){
                if (allHeight[j]<minAllHeight){
                    minAllHeight=allHeight[j];
                    indx=j;
                }
            }

          $cur.css({
                "left":indx*$cur.outerWidth(true),
                "top":minAllHeight
            });
            allHeight[indx]=minAllHeight+$cur.outerHeight(true);
        })

        }

        waterFall();

        $(window).on("resize",function () {
            waterFall()
        })

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

代码预览地址:

https://github.com/have-not-BUG/task/blob/master/renwu/renwu30/renwu30.html

**本文版权归本人即简书笔名:该账户已被查封 所有,如需转载请注明出处。谢谢! *

上一篇 下一篇

猜你喜欢

热点阅读