思路还是很简单
(1)先初始化一个数组,找到最小的值和它的索引,
(2)根据这两个值设置div的位置(距离左边和顶部)
(3)最后把数组对应索引位置高度加上此节点高度,继续循环
<html><head>
<meta charset="utf-8">
<title>瀑布流</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
ul li {
list-style: none;
}
.clearfix {
*zoom: 1;
}
.clearfix:after {
display: block;
content: '';
clear: both;
}
a {
text-decoration: none;
color: #333;
font-size: 14px;
}
.content {
position: relative;
}
.item {
position: absolute;
width: 200px;
margin-right: 10px;
margin-top: 10px;
transition: all 1s;
}
.h1 {
height: 200px;
background-color: #f4b300;
}
.h2 {
height: 300px;
background-color: #691bb8;
}
.h3 {
height: 400px;
background-color: #006ac1;
}
.img-preview {
width: 1000px;
margin: 0 auto;
}
.img-row {
margin-bottom: 8px;
}
.img-row:after {
content: "";
display: block;
clear: both;
}
.img-box {
float: left;
}
.img-line .img-box:first-child {
padding-left: 0;
}
</style>
</head>
<body>
<div class="content">
<div class="item h1" style="left: 0px; top: 0px;">1</div>
<div class="item h3" style="left: 210px; top: 0px;">2</div>
<div class="item h2" style="left: 420px; top: 0px;">3</div>
<div class="item h1" style="left: 630px; top: 0px;">4</div>
<div class="item h1" style="left: 840px; top: 0px;">5</div>
<div class="item h3" style="left: 1050px; top: 0px;">6</div>
<div class="item h3" style="left: 1260px; top: 0px;">7</div>
<div class="item h2" style="left: 1470px; top: 0px;">8</div>
<div class="item h1" style="left: 0px; top: 210px;">9</div>
<div class="item h3" style="left: 630px; top: 210px;">10</div>
<div class="item h3" style="left: 840px; top: 210px;">11</div>
<div class="item h3" style="left: 420px; top: 310px;">12</div>
<div class="item h2" style="left: 1470px; top: 310px;">13</div>
<div class="item h2" style="left: 210px; top: 410px;">14</div>
<div id="load-more"></div>
</div>
<script src="js/jquery-1.11.1.min.js"></script>
<script>
$(window).on('resize', function () {
render();
});
function render() {
var ctWidth = $(window).width()
, itemWidth = $('.item').outerWidth(true)
, colNum = Math.floor(ctWidth / itemWidth);
var colSumHeight = [];
for (var i = 0; i < colNum; i++) {
colSumHeight.push(0);
}
$('.item').each(function () {
var $node = $(this);
var idx = 0,
minSumHeight = colSumHeight[0];
for (var i = 0; i < colSumHeight.length; i++) {
if (colSumHeight[i] < minSumHeight) {
idx = i;
minSumHeight = colSumHeight[i];
}
}
$node.css({
left: itemWidth * idx,
top: minSumHeight
});
colSumHeight[idx] = $node.outerHeight(true) + colSumHeight[idx];
})
}
render();
</script>
</body></html>