在一些网站中会用到图片的瀑布流效果,图片的宽度固定而高度不固定,对这样的图片进行排列,具体实现如下:
.cont{
margin: 0 auto;position: relative;}
.box{
float: left;padding: 4px;}
.imgbox{
border: solid 1px #000;padding: 4px;border-radius: 4px;}
.imgbox img{
width: 200px;display: block;}
js写在head里,因此需要写在onload函数里:
onload = function(){
var wf = new WaterF();
wf.init();
}
class WaterF{
constructor(){
this.cont = document.querySelector(".cont");
this.abox = document.querySelectorAll(".box");
// 获取页面的宽度
this.clientW = document.documentElement.clientWidth;
}
init(){
// 计算得到在页面一行能放几个box
this.maxNum = parseInt(this.clientW / this.abox[0].offsetWidth);
// 给cont设置宽度为一个box的宽度乘一行最多放置的个数的宽度
this.cont.style.width = this.abox[0].offsetWidth * this.maxNum + "px";
// 完善布局之后,需要区分第一行和其他行
// console.log(this);
this.firstLine();
this.otherLine();
}
firstLine(){
// 在第一行,获取所有元素的高度,放在一个数组内,用以得到最小高度
this.heightArr = [];
for(var i = 0;i<this.maxNum;i++){
this.heightArr.push(this.abox[i].offsetHeight);
}
// console.log(this.heightArr);
}
otherLine(){
// 需要拿到后面行的所有元素
for(var i = this.maxNum;i<this.abox.length;i++){
// 获取第一行的最小值和最小值的索引
var min = Math.min(...this.heightArr);
// console.log(min);
var minIndex = this.heightArr.indexOf(min);
// console.log(minIndex);
// 设置定位
this.abox[i].style.position = "absolute";
// 根据最小值设置top
this.abox[i].style.top = min + "px";
// 根据最小值设置left
this.abox[i].style.left = minIndex * this.abox[0].offsetWidth + "px";
// 修改最小值
this.heightArr[minIndex] = this.heightArr[minIndex] + this.abox[i].offsetHeight;
}
}
}
html代码,因为需要对cont或许宽度,所以如果给box设置margin会导致宽度计算不正确,因此只能给box设置padding值才能实现图片与图片的距离,某些情况下,图片下方会添加文字,所以给图片和文字写一个共同的imgbox,本篇文章只写图片,具体代码如下:
<div class="cont">