content
Native waterfall flow analysis and concrete realization
Repeated ideas
①: What is waterfall flow:
②: Requirements: the picture is not deformed, and the display area is not blank.
③: Analysis of the requirements: the pictures follow the style of equal width and unequal height.
Note: the first row of pictures can be processed (let css operate its style), start from the second row , Each picture needs to be traversed and appended 追加的位置是每一次高度最低的位置(凹陷处
.
Example implementation
js code block (nanny-level comments)
window.addEventListener('load', () => {
var boxWidth = document.querySelector('.box').offsetWidth; // # 求出一个盒子的宽度(offsetWidth 返回值包括 padding)
var containerWidth = document.querySelector('.container').offsetWidth; // # 求出父容器的宽度
var col = parseInt(containerWidth / boxWidth) //# 求出一排有几列
var boxs = document.querySelectorAll('.box'); //# 拿到所有的盒子,优化计算
var heightArr = []; //# 定义空数组,来装每一排图片的高度
boxs.forEach((item, index) => {
//# 遍历所有盒子
if (index < col) {
heightArr[index] = item.offsetHeight; //# 如果是第一排,直接排序(不定位),且每一次循环把图片高度装入数组
} else {
var minHeightBox = Math.min(...heightArr); //# 求出一排中最小高度的图片(每次追加图片至最小高度下)
var minHeightIndex = heightArr.findIndex(item => item == minHeightBox); //# 找出最小高度图片的索引
item.style.position = 'absolute'; //# 从第二排起,每张图片都要定位追加
item.style.top = minHeightBox + 'px'; //# 距顶部等于最小图片的高度
item.style.left = minHeightIndex * boxWidth + 'px'; // # 距左侧等于最小图片的索引 * 每个盒子的宽度(切记盒子等宽不等高)
heightArr[minHeightIndex] += item.offsetHeight; //# 图片加入后,把其高度追加入数组。确保后续追加
}
})
})
For the css demo, I am ashamed to be ugly, so I won't show it.
Tips: You can print out the real-time size of the browser window when you deduct the code, which is convenient for calculation.