简单瀑布流布局

 三列,每列之间的间隔是10px,每个div高度50-250px

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        section.wrapper {
            width: 1260px;
            margin: 0 auto;
        }

        section.wrapper:after {
            content: '';
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }

        section.wrapper div.column {
            float: left;
            width: 400px;
            padding: 10px;
        }

        .wrapper .waterfall-box {
            width: 400px;
            margin-bottom: 10px;
            background-color: pink;
        }

    </style>

</head>
<body>
<section class="wrapper">
    <div id="div0" class="column"></div>
    <div id="div1" class="column"></div>
    <div id="div2" class="column"></div>
</section>

<script>

    var yArr = [10, 10, 10];
    const GAP = 10;

    for (var i = 0; i < 8; i++) {
        waterfall();

    }

    function waterfall() {
        var height = parseInt(50 + 200 * Math.random());


        var box = document.createElement('div');
        box.className = 'waterfall-box';
        box.style.height = height + 'px';

        var minY = findMin(yArr);
        yArr[minY.minIndex] += height + GAP;

        var div = document.getElementById('div' + minY.minIndex);
        div.appendChild(box);

        function findMin(arr) {
            var minEle,
                minIndex;
            arr.forEach(function (ele, index, arr) {
                if (minEle === undefined || minEle > ele) {
                    minEle = ele;
                    minIndex = index;
                }
            })
            return {
                minEle: minEle,
                minIndex: minIndex
            }
        }

    }

    

</script>

</body>
</html>

 

posted on 2017-05-11 18:11  zmiaozzz  阅读(157)  评论(0编辑  收藏  举报

导航