瀑布流:所有图片宽度相等,高度不相等
第一行从左到右排好,第二行的第一个在第一行高度最小的下面,第二个在第一行第二小的....
(1)HTML部分
<div class="cont">
<div class="box">
<div class="imgbox">
<img src="./imgs/m2.jpg" alt="">
</div>
</div>
<div class="box">
<div class="imgbox">
<img src="./imgs/1.jpg" alt="">
</div>
</div>
.
.
.
</div>
(2)CSS部分
/* 大容器 */
.cont {
margin: 0 auto;
/* 宽度js计算 浏览器总宽/任意imgbox宽=几个,向下取整;个数*imgbox宽=cont宽*/
height: 1000px;
background: #ccc;
position: relative;
}
/* 图片盒子外面再套盒子 不能写imgbox的margin,不然js不好计算 */
.box {
padding: 6px;
float: left;
}
.imgbox {
padding: 6px;
border: 1px solid;
border-radius: 6px;
}
.imgbox img {
width: 200px;
}
(3)JS部分
onload = function() {
new WaterfallFlow();
}
class WaterfallFlow {
constructor() {
this.cont = document.querySelector(".cont"); //大容器
this.box = document.querySelectorAll(".cont .box"); //所有图片盒子
this.init();
this.firstLine();
this.otherLine();
}
// 补全布局
init() {
// 浏览器总宽/imgbox宽=最多放几个,向下取整;个数*imgbox宽=cont宽
this.maxNum = parseInt(document.documentElement.clientWidth / this.box[0].offsetWidth);
this.cont.style.width = this.maxNum * this.box[0].offsetWidth + "px";
}
// 第一行
firstLine() {
// 遍历 把每个盒子的高度都存放在一个新数组内
this.heightArr = [];
for (let i = 0; i < this.maxNum; i++) {
this.heightArr.push(this.box[i].offsetHeight);
}
}
// 其他行
otherLine() {
// 从第一行的几个开始 到所有的最后
for (let i = this.maxNum; i < this.box.length; i++) {
// 其他行要定位
this.box[i].style.position = "absolute";
// Math.min里不能写数组 要展开,获取第一行高度最小的
const min = Math.min(...this.heightArr);
// 最小索引
const minIndex = this.heightArr.indexOf(min);
// 下一行所在的top=上个最小高的
this.box[i].style.top = min + "px";
// 下一行所在的left=最小索引*图片宽度 (在第三个 前面就乘两个)
this.box[i].style.left = minIndex * this.box[0].offsetWidth + "px";
// 修改初始最小的列高..循环 (最小高加上底下的高)
this.heightArr[minIndex] += this.box[i].offsetHeight;
}
}
}