您的位置:首页 > Web前端 > JavaScript

JavaScript实现瀑布流布局

2017-04-17 23:33 555 查看
在一些购物类网站上会看到一种诸如下图的类似瀑布流布局,这种布局的一个特点是每一个盒子的宽度相同,而高度却是任意的。



<div class="pic-box">
<div class="pic">
<img src="img/1.jpg" alt="1">
</div>
</div>


通过一个div.pic-box盒子来控制每个元素之间的间隔,div.pic来给元素添加边框效果。由于后面div.pic-box需要绝对定位,所以给它的父元素一个position: relative;属性。每个img的宽度设置为200px;

js脚本的编写主要有几个思路:

1. 每一列排列的元素个数随浏览器宽度改变而改变

2. 先将第一排元素排列好,然后后面的元素找前面高度最小的那一列插进去

注意: 每次将元素插进去的时候需要更新每一列高度值得数组

function waterfall(parent,box){
let oParent = document.getElementById(parent);
let oBoxs = oParent.getElementsByClassName(box);
let boxWidth = oBoxs[0].offsetWidth;
let screenWidth = document.body.clientWidth || document.documentElement.Width;
let cols = Math.floor(screenWidth/boxWidth);//每一排有多少列
oParent.style.width = boxWidth * cols + 'px';
oParent.style.margin = '0 auto';
let aBoxHeight = [];
//第一排的照片正常排列,第二排开始每一张照片找到上一排照片最短高度的地方插入
for(let i = 0,lens = oBoxs.length;i < lens;i++){
if(i < cols){
aBoxHeight.push(oBoxs[i].offsetHeight);
}else {
let minHeight = Math.min.apply(null,aBoxHeight);
let index = getIndex(aBoxHeight,minHeight);
oBoxs[i].style.position = "absolute";
oBoxs[i].style.top = aBoxHeight[index] +"px";
oBoxs[i].style.left = oBoxs[index].offsetLeft + "px";
aBoxHeight[index] += oBoxs[i].offsetHeight;
}
}
}
function getIndex(arr,val){
for(let i = 0,lens = arr.length;i < lens;i++){
if(arr[i] === val){
return i;
}
}
}


这样就实现了瀑布流的布局,如果还要实现往先滚动实时加载图片,还需要添加一个滚动事件的监听。

let data = [{"src":"img/1.jpg"},{"src":"img/22.jpg"},{"src":"img/13.jpg"},{"src":"img/14.jpg"},{"src":"img/5.jpg"},{"src":"img/16.jpg"}];
//添加滚动监听函数,自动加载图片
window.addEventListener("scroll",function(event){
if(checkScroll("container","pic-box")){
for(let i = 0,lens = data.length;i < lens;i++){
let box = document.createElement("div");
box.className = "pic-box";
let pic = document.createElement("div");
pic.className = "pic";
let img = document.createElement("img");
img.src = data[i].src;
img.alt = i;
pic.appendChild(img);
box.appendChild(pic);
document.getElementById("container").appendChild(box);
waterfall("container","pic-box");
}
}
});

function checkScroll(parent,box){
let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
let screenHeight = document.body.clientHeight || document.documentElement.clientHeight;
let oParent = document.getElementById(parent);
let oBoxs = oParent.getElementsByClassName(box);
let lastBox = oBoxs[oBoxs.length - 1];
let offset = lastBox.offsetTop + Math.floor(lastBox.offsetHeight/2);
return offset > scrollTop + screenHeight? false : true;
}


当最后一个元素的一半高度都通过了浏览器底部的时候,会自动加载新的图片进来。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: