<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>瀑布流布局</title>
<script src="./jquery.js"></script>
<style>
* {margin: 0;padding: 0;}
.img {padding: 10px;float: left;}
.img img {width: 200px;border: 1px solid #ccc;}
</style>
</head>
<body>
<div class="main">
<div class="img"><img src="./img/1.jpg" alt="" class="src"></div>
<div class="img"><img src="./img/2.jpg" alt="" class="src"></div>
<div class="img"><img src="./img/3.jpg" alt="" class="src"></div>
<div class="img"><img src="./img/4.jpg" alt="" class="src"></div>
<div class="img"><img src="./img/5.jpg" alt="" class="src"></div>
<div class="img"><img src="./img/6.jpg" alt="" class="src"></div>
<div class="img"><img src="./img/7.jpg" alt="" class="src"></div>
<div class="img"><img src="./img/timg.jpg" alt="" class="src"></div>
</div>
<script>
$(window).on('load', function() { //dom、图片等加载完成
//求一共多少列
var allImg = $(".main .img");
//图片框的宽度outerWidth()包含padding和border
var imgDivWidth = allImg.outerWidth();
//整个屏幕的宽度
var screenWidth = $(window).width();
//求列数
var cols = parseInt(screenWidth / imgDivWidth);
console.log(cols);
//获取高度
var heightArr = [];
$.each(allImg, function(index, item) {
var boxHeight = $(item).outerHeight(); //每张图片的高度
if (index < cols) { //第一排
heightArr[index] = boxHeight;
} else { //换行
//最小高度
var minDivHegith = Math.min.apply(Math.min, heightArr);
// var min = heightArr[0];
// heightArr.forEach(function(item){ forEach循环求最小值
// if(min>item){
// min = item;
// }
// });
//最小高度的索引$.inArray(要找的值,数组),返回索引,没有找到返回-1
var i = $.inArray(minDivHegith, heightArr);
console.log(heightArr)
// var index = heightArr.indexOf(minDivHegith);
$(item).css({
position: 'absolute',
left: i * imgDivWidth + 'px',
top: minDivHegith + 'px'
})
//最小高度改变
heightArr[i] += minDivHegith;
}
})
})
$(function() { //dom加载完成,这是图片可能还没有加载完成,会造成bug,所以用$(window).on('load', function(){})
});
</script>
</body>
</html>