效果图:
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
</html>
<script src="jQuery.js" charset="utf-8"></script>
<script type="text/javascript">
class waterFall{
constructor(){
this.arrH = [];
}
createDiv(){
for(let i = 0; i < 10; i++){
let oDiv = $(`<div>${i}</div>`);
let h = Math.round(Math.random()*300 + 50);//随机高度50到350
oDiv.css({
position:"absolute",
width: 300,//固定宽度
height: h,
backgroundSize:`300px ${h}px`
});
$("body").append(oDiv);
}
this.setPic();
}
setPic(){
this.arrH = [];
let n = parseInt($(window).innerWidth() / 300);
let that = this;
$("div").each(function(index, el) {//这里每次生成10个div,$("div")会获取所有的div
if(index < n){
$(el).offset({
left:index * 300 + index * 10,
top:0
});
that.arrH.push($(el).height());
}else{
let minIndex = that.findMin(that.arrH);
$(el).offset({
left:minIndex * 300 + minIndex * 10,
top:that.arrH[minIndex] + 10
});
that.arrH[minIndex] += $(el).height() + 10;//数组高度更新,要加上本次的高度再+10,形成10的间隙
}
that.lazyLoad(index,el);//使用懒加载进行判断
});
}
findMin(arr){
let min = 0;
$.each(arr,function(index, el) {
if(arr[min] > arr[index]){
min = index;
}
});
return min;
}
onscroll(){
let that = this;
$(window).scroll(function() {
if(Math.max.apply(null,that.arrH) - 10 < $(window).innerHeight() + $(window).scrollTop()){//这里减10是因为高度数组里多加了10,不然可视高度+滚动条高度永远也没高度数组里最大的那个值大
that.createDiv();
}
});
}
lazyLoad(index,ele){
// console.log($(ele).css("backgroundImage"));
//if判断背景图到底有没有,没有的话再进入条件
if($(ele).css("backgroundImage") == "none"){
$(ele).css("backgroundImage",`url(img/pic${index%10+1}.png)`);//在这里赋给背景图的值可以减少对服务器的请求.
}
}
}
let w = new waterFall();
w.createDiv();
// w.createDiv();//放的图有点少,再加一个为方便形成滚动条,
w.onscroll();
</script>