瀑布流 瀑布流布局 JS瀑布流
程序员文章站
2022-06-01 23:22:52
...
思路
通过容器相对定位, 视图块绝对定位的方式来布局, 通过计算和对比将每一张图追加至最短的一列
注意点
在计算每一个视图块的宽度的时候需要算上 视图块 与 视图块 之间的边距
效果图
步骤
- 计算每一列图片的宽度
- 按顺序先渲染出第一行
- 找出最短的一列并将下一个视图块 渲染至 最短列
代码示例
HTML 代码
<body>
<div class="box">
<div class="item">
<img src="banner.jpg" alt="" />
</div>
<div class="item">
<img src="show.jpg" alt="" />
</div>
<div class="item">
<img src="cloth.jpg" alt="" />
</div>
<div class="item">
<img src="banner.jpg" alt="" />
</div>
<div class="item">
<img src="show.jpg" alt="" />
</div>
<div class="item">
<img src="cloth.jpg" alt="" />
</div>
<div class="item">
<img src="banner.jpg" alt="" />
</div>
<div class="item">
<img src="show.jpg" alt="" />
</div>
<div class="item">
<img src="cloth.jpg" alt="" />
</div>
<div class="item">
<img src="show.jpg" alt="" />
</div>
<div class="item">
<img src="cloth.jpg" alt="" />
</div>
<div class="item">
<img src="banner.jpg" alt="" />
</div>
</div>
</body>
css 代码
<style>
.box {
width: 100%;
position: relative;
}
.item {
position: absolute;
}
.item img {
width: 100%;
height: 100%;
}
</style>
JS代码
<script>
var HeightList = [0, 0, 0]; // 记录没列的高度
var i = 1; // 当前循环添加图片的位置,从第 1 张开始循环添加
function waterFall() {
// 页面宽度 = 窗口的宽度 - 滚动条宽度
var pageWidth = getClient().width - 8;
var columns = 3; //3列
var itemWidth = parseInt(pageWidth / columns) - 10; // 计算每一个 item 的宽度
let itemList = document.querySelectorAll(".item"); // 获取所有的 item
var arr = [];
itemList.forEach(item => {
item.style.width = `${itemWidth}px`; // 设置 item 的宽度
let height = item.children[0].style.height; // 获取 item 的高度(用于累计每列的高度)
if (i <= 3) {
// 第一排直接追加
item.style.left = `${itemWidth * (i - 1) + 10 * (i - 1)}px`;
cumulativeHeight(i - 1, item.offsetHeight);
} else {
// 如果不是第一排需要找到最短的一列再进行追加
let remainder = findMin();
item.style.left = `${itemWidth * remainder + 10 * remainder}px`;
item.style.top = `${HeightList[remainder]}px`;
cumulativeHeight(remainder, item.offsetHeight);
}
// 每追加一次, 下标自增一次
++i;
})
}
/**
* @author: yx
* @method: 累加计算当前行高
* @param { i: 行下标, height: 行高度 }
*/
function cumulativeHeight(i, height) {
HeightList[i] += (height + 10);
}
// 找到最短一列的下标 [0, 1, 2]
function findMin() {
return HeightList[0] < HeightList[1] ? HeightList[0] < HeightList[2] ? 0 : 2 : HeightList[1] < HeightList[2] ? 1 : 2;
}
// 获取窗口高宽 clientWidth 处理兼容性
function getClient() {
return {
width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
}
}
// 重置每列高度和当前图片的循环位置
function reset(){
HeightList = [0, 0, 0];
i = 0;
}
// 页面尺寸改变时实时触发
window.onresize = function () {
// 重新定义瀑布流
reset();
waterFall();
};
// 初始化
window.onload = function () {
// 实现瀑布流
reset();
waterFall();
}
</script>
下一篇: 重签名ipa