瀑布流不是实现原理:
1.瀑布流的布局,要求布局的元素是等宽的,瀑布流布局的特点就是等宽不等高,然后计算元素的宽度和浏览器屏幕宽度的比值,确定出列数
2.创建一个数组,这个数组用于存储第一行图片的各个高度
3.计算出这个数组中最小的元素,接下来的图片通过定位的方式布局到高度最小的图片下面,
4.最后将这个最小高度进行更新,然后一直循环地布局下去
$(window).on("load", function () {
watchFall()
})
function watchFall() {
var boxs = $(".box")
var boxWidth = boxs.outerWidth()
var screenWidth = $(window).width()
var cols = parseInt(screenWidth / boxWidth)
//存储图片的高度
var heightArr = []
console.log(heightArr)
$.each(boxs, function (index, item) {
var imgHeight = $(item).outerHeight();
if (index < cols) {
heightArr[index] = imgHeight
} else {
//找到第一列中最小的高度,left:最小高度的索引*width top:最小高度+“px”
var minHeight = Math.min(...heightArr)
// console.log(minHeight)
var minIndex = $.inArray(minHeight, heightArr)
// console.log(minIndex)
$(item).css({
position: "absolute",
left: minIndex * boxWidth + "px",
top: minHeight + "px"
})
//更新最小的高度
heightArr[minIndex] += imgHeight
// console.log(heightArr)
}
})
}