js 实现瀑布流

<style>
        div{
            background: #ccc;
            width: 200px;
            position: absolute;
            transition:0.5s;
        }
    </style>
<script>
    window.onload = function(){
        adddiv();
        function adddiv(){
            for (var i = 0;i<20;i++){
                var div = document.createElement('div');
                div.style.width = 200 + "px";
                div.style.backgroundColor = "green";
                div.innerHTML = i;
                div.style.height = Math.floor(Math.random()*200+50)+"px";
                document.body.appendChild(div);
            }
            change();
        }
        function change(){
            var aDiv = document.getElementsByTagName('div');

            var clientwidth = document.documentElement.clientWidth;

            var n = Math.floor(clientwidth/200);
            if (n<=0) return

            var center = (clientwidth - n*200)/2; //左右应该留下的边距

            var arrH = [];//最大值为n

            for (var i = 0;i<aDiv.length;i++){
                var j = i%n;//取余表示一行中的第几个div

                if (arrH.length==n) {                    //从第二行开始按此方法排列
                    var min = findMin(arrH);          //从最“矮”的排起,可以从下图的序号中看得出来,下一行中序号是从矮到高排列的
                    aDiv[i].style.left =center + min*210 + "px";
                    aDiv[i].style.top = arrH[min]+10 + "px";
                    arrH[min] += aDiv[i].offsetHeight + 10;
                    // alert(min);
                }else{
                    //第一行排列情况
                    arrH[j] = aDiv[i].offsetHeight;
                    aDiv[i].style.left =center + 200*j+10*j + "px";
                    aDiv[i].style.top = 0;
                }
            }
        }
        function findMin(arr) {
            var m = 0;
            for (var i = 0; i < arr.length; i++) {
                m = Math.min(arr[m], arr[i]) == arr[m] ? m : i;
            }
            return m;
        }
    }

</script>

 

posted @ 2017-08-23 20:35  RoadAspen  阅读(176)  评论(0编辑  收藏  举报