瀑布流布局

这是html,首先先定义一个容器ct,里面的div模拟照片,每张照片的宽度一样,高度不一样

JS Bin1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

function waterFull() { var $ctWidth = $('.ct').width(), //获取容器宽度 $nodeWidth = $('.item').width(), //获取每个节点宽度 colLength = parseInt($ctWidth / $nodeWidth), //获取页面每一行数量 itemArr = []; //初始化数组 for (var i = 0; i < colLength; i++) { itemArr[i] = 0; //遍利数组 } $('.item').each(function() { var minValue = https://www.it610.com/article/Math.min.apply(null, itemArr); //获取最小值 var minIndex = itemArr.indexOf(minValue); //获取最小的索引值 $(this).css({ //定义位置 top: itemArr[minIndex], // left: $(this).outerWidth(true) * minIndex }); itemArr[minIndex] += $(this).outerHeight(true); }); }

1、定义好瀑布流函数,
2、然后获取容器的宽度,和每个节点的宽度,因为我们要得到容器里面有几列,初始化数组,让item为0
3、遍历节点数组
4、通过Math.min.apply(null, itemArr)获取到最小值,和最小值的下标
5、最上面开始摆放最小值的下标对应的值,往左偏移的距离是最小的那个的宽度
6、数组的最小值的高度变化
最后还可以优化下代码,将代码进行封装
var Render = (function () { function init() { waterFull(); $(window).resize(function () { //窗口尺寸每次变化,执行一次瀑布流 waterFull(); }); } function waterFull() { var $ctWidth = $('.ct').width(),//获取容器宽度 $nodeWidth = $('.item').width(),//获取每个节点宽度 colLength = parseInt($ctWidth / $nodeWidth),//获取页面每一行数量 itemArr = []; //初始化数组 for (var i = 0; i < colLength; i++) { itemArr[i] = 0; //便利数组 } $('.item').each(function () { var minValue = https://www.it610.com/article/Math.min.apply(null, itemArr); //获取最小值 var minIndex = itemArr.indexOf(minValue); //获取最小的索引值 $(this).css({//定义位置 top: itemArr[minIndex],// left: $(this).outerWidth(true) * minIndex }); itemArr[minIndex] += $(this).outerHeight(true); }); } return { init: init }; })(); Render.init();

【瀑布流布局】瀑布流布局的实现

    推荐阅读