该方法仅满足,元素等宽,高度一般不同的瀑布流布局
- 计算元素宽度与浏览器宽度之比,得到布局列数;
- 将未布局的元素依次布局至高度最小的那一列;
- 页面滚动时继续加载数据,动态地渲染在页面上。
<div id="parent">
<div id="masonry_container">
<div class="masonry_item" v-for="(item,index) in 10" :key="index">
<h3>标题{{index+1}}</h3>
<p>内容{{index+1}}</p>
</div>
</div>
</div>
masonryLayouts(marginLeft = 0, marginTop = 0){ // 瀑布流布局
var containerWidth=document.getElementById("masonry_container").width; // 容器的宽度
var eleWidth=500; // 每个元素宽度为500px
var cols=parseInt(containerWidth/eleWidth); // 瀑布流布局的列数
document.getElementById("masonry_container").style.width=eleWidth*cols+"px";
// 设置容器宽度,为了居中显示,添加position:relative
var colsHeight=new Array(cols).fill(0);; // 保存每列当前高度,初始为0
var eles=document.getElementsByClassName("masonry_item");
for(var i=0;i<eles.length;i++){
var minHeightCol=0; // 保存当前最短列的索引
for(var j=1;j<cols;j++){
if(colsHeight[j]<colsHeight[minHeightCol]){
minHeightCol=j;
}
}
eles[i].style.left=eleWidth*minHeightCol + marginLeft +"px"; // 元素定位
eles[i].style.top=colsHeight[minHeightCol] +"px";
// position: absolute,定位添加左边距和上边距
colsHeight[minHeightCol]+=(window.getComputedStyle(eles[i]).height)+marginTop ; // 更改当前列高度
document.getElementById('masonry_container').style.height = `${colsHeight[minHeightCol] + 100}px`; // 把父容器的高度撑开
}
}