分析:
1. 大盒子
2. 所有的子节点
3. 计算大盒子的宽度
4. 计算一个子节点的宽度
5. 计算列数 (总宽度 / 子节点的宽度)
6. 计算左右间隙(总宽度 - 列数 * 子节点的宽度) / (列数 + 1)
7. 初始化第一行所有列的位置(left / top) 难点
8. 对号入座
最小高度的列的下标
*/
window.onload = function(){
waterFall('wrap');
}
window.onresize = function(){
waterFall('wrap');
}
function waterFall(id,childName,space){
//1. 初始化参数
if(!id){return;}
childName = childName || 'div';
space = space || 10;
//2. 获取大盒子
let oBigBox = document.getElementById(id);
//3. 所有的子节点
// let oChilds = oBigBox.getElementsByTagName(childName);
let oChilds = oBigBox.children;
//4. 计算大盒子的宽度
let bigBoxWidth = oBigBox.offsetWidth;
//5. 计算一个子节点的宽度
let childWidth = oChilds[0].offsetWidth;
//6. 计算列数 (总宽度 / 子节点的宽度)
let colNum = Math.floor(bigBoxWidth / childWidth);
//7. 计算左右间隙(总宽度 - 列数 * 子节点的宽度) / (列数 + 1)
let padding = Math.floor((bigBoxWidth - colNum * childWidth) / (colNum + 1));
//8. 初始化第一行所有列的位置(left / top) 难点
let arr = [];
for(let i = 0;i < colNum ; i ++){
let obj = {};
obj.left = i * childWidth + (i + 1) * padding;
obj.top = space;
arr.push(obj);
}
//9. 对号入座
for(let i = 0,len = oChilds.length;i < len;i ++){
oChilds[i].style.position = 'absolute';
let index = minHeight(arr);
oChilds[i].style.left = arr[index].left + 'px';
oChilds[i].style.top = arr[index].top + 'px';
arr[index].top += oChilds[i].offsetHeight + space;
oBigBox.style.height = arr[index].top + 'px';
}
}
//最小高度列的下标
function minHeight(arr){
let index = 0;
let min = arr[0].top;
arr.forEach(function(value,i){
if(min > value.top){
min = value.top;
index = i;
}
})
return index;
}
</script>
自适应瀑布流
最新推荐文章于 2021-09-16 21:29:56 发布