推荐答案
// www.javascriptcn.com code example
function waterfallLayout(containerSelector, itemSelector, columnCount) {
const container = document.querySelector(containerSelector);
const items = document.querySelectorAll(itemSelector);
const columnHeights = new Array(columnCount).fill(0);
const gap = 10; // 假设每个元素之间的间距为10px
items.forEach(item => {
const minHeightIndex = columnHeights.indexOf(Math.min(...columnHeights));
item.style.position = 'absolute';
item.style.left = `${minHeightIndex * (item.offsetWidth + gap)}px`;
item.style.top = `${columnHeights[minHeightIndex]}px`;
columnHeights[minHeightIndex] += item.offsetHeight + gap;
});
container.style.position = 'relative';
container.style.height = `${Math.max(...columnHeights)}px`;
}本题详细解读
1. 函数参数
containerSelector: 容器的选择器,用于指定瀑布流布局的父容器。
itemSelector: 子元素的选择器,用于指定需要进行瀑布流布局的子元素。
columnCount: 列数,决定瀑布流布局的列数。
2. 实现步骤
- 获取容器和子元素:通过
document.querySelector 和 document.querySelectorAll 获取容器和子元素。
- 初始化列高度数组:创建一个长度为
columnCount 的数组 columnHeights,并初始化为0,用于记录每一列的当前高度。
- 遍历子元素:
- 找到当前高度最小的列。
- 将子元素定位到该列的下方,并更新该列的高度。
- 设置容器高度:根据所有列的最大高度,设置容器的高度,以确保所有子元素都能显示在容器内。
3. 关键点
- 绝对定位:通过
position: absolute 将子元素定位到指定位置。
- 列高度管理:通过
columnHeights 数组记录每一列的当前高度,确保子元素能够正确地排列在列的下方。
- 容器高度调整:根据列的最大高度调整容器的高度,避免子元素溢出容器。
4. 注意事项
- 间距处理:代码中假设每个子元素之间的间距为10px,可以根据实际需求调整。
- 响应式布局:如果需要实现响应式布局,可以在窗口大小变化时重新调用该函数,重新计算布局。