简单实现流布局
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>DEMO5</title> <meta charset="utf-8" /> <script src="js/jquery-1.11.3.min.js"></script> </head> <body> <div id="container" style="border:1px solid red;padding:10px;text-align:center;display:flex;"></div> <script type="text/javascript"> $(function () { //初始化测试项 var screenWidth = 600; //容器宽度 var itemColumn = 5; //列数量 var itemWidth = parseInt((screenWidth - 20) / itemColumn); //每列的宽度 $('#container').css("width", screenWidth); //设置容器宽度 //初始化测试数据 var objs = InitTestData(); //处理 var itemOjbArr = InitItemArr(itemColumn); $.each(objs, function (index, obj) { var minIndex = FindMinLengthIndex(itemOjbArr); itemOjbArr[minIndex].items.push(obj); itemOjbArr[minIndex].itemHeight += parseInt(obj.height); }); //展示 $.each(itemOjbArr, function (index, obj) { $('#container').append(RenderHtml(obj.items, itemWidth)); }); }); //找出最小高度的索引 function FindMinLengthIndex(itemArr) { var index = itemArr.length - 1; var height = itemArr[index].itemHeight; for (i = index; i >= 0; i--) { var item = itemArr[i]; if (item.itemHeight <= height) { index = i; height = item.itemHeight; } } return index; } //初始化Item数组 function InitItemArr(length) { var arr = []; for (i = 0; i < length; i++) { arr.push({ itemHeight: 0, items:[] }); } return arr; } //初始化测试数据 function InitTestData() { var objs = []; for (var i = 1; i <= 15; i++) { objs.push({ width: 289, height: RandomWidth(200, 400), text: i }); } return objs; } //获取指定区间的随机数 function RandomWidth(n, m) { var random = Math.floor(Math.random() * (m - n + 1) + n); return random; } //处理html function RenderHtml(itemArr, imageWidth) { var itemHtml = '<div style="flex:1">'; $.each(itemArr, function (index, arr) { var imageHeight = parseInt(arr.height * (imageWidth / arr.width)); var _tempHtml = ''; _tempHtml += '<div>'; _tempHtml += '<image src="1.jpg" width="' + imageWidth + '" height="' + imageHeight + '" /><br/>'; _tempHtml += arr.text; _tempHtml += '</div>'; itemHtml += _tempHtml; }); itemHtml += '</div>'; return itemHtml; } </script> </body> </html>