js实现瀑布流(内容适配屏幕宽度)

161 阅读1分钟
function waterFall() {
        // 220为内容宽度自行调整 获取当前页面需要几列
        var columns = Math.round($(document.body).outerWidth(true) / 220)
        // 设置
        var pageWidth = $(document.body).outerWidth(true) - columns * 10;
        var itemWidth = parseInt(pageWidth / columns); //得到item的宽度
        var arr = [];
        $(".ContentList .listItem").each(function (i) {
            var height = $(this).height();
            if (i < columns) {
                // 第一行按序排列
                $(this).css({
                    top: '20px',
                    left: (itemWidth) * i+15 * i, 
                });
                //将行高push到数组
                arr.push(height);
                // 设置外层div高度(子元素是绝对定位,不占位)
                $('.ContentList').height(height)
            } else {
                // 其他行
                // 拿到第一行的高度 设置其他行的top
                var minHeight = arr[0];
                var index = 0;
                for (var j = 0; j < arr.length; j++) {
                    if (minHeight > arr[j]) {
                        minHeight = arr[j];
                        index = j;
                    }
                }
                $(this).css({
                    top: arr[index] + 50, //设置50的距离
                    left: $(".ContentList .listItem").eq(index).css("left")
                });
               // 设置外层div高度(子元素是绝对定位,不占位)
                $('.ContentList').height(arr[index] + 50 + height)
                arr[index] = arr[index] + height + 30; //设置30的距离
            }
        });
    }

\

<div class="ContentList ">
     <div class="listItem"></div>
     <div class="listItem"></div>
     <div class="listItem"></div>
     <div class="listItem"></div>
     <div class="listItem"></div>
</div>

\