瀑布流大家都见过吧,展示一下
先排个html
<div id="wrapper">
<div class="box">
<div class="photo">
<img src="./images/0.jpg" alt="">
</div>
</div>
<div class="box">
<div class="photo">
<img src="./images/1.jpg" alt="">
</div>
</div>
<div class="box">
<div class="photo">
<img src="./images/2.jpg" alt="">
</div>
</div>
<div class="box">
<div class="photo">
<img src="./images/3.jpg" alt="">
</div>
</div>
给他设置样式
#wrapper{
width: 1200px;
height: auto;
background-color: pink;
margin: 0 auto;
position: relative;
.box{
float: left;
padding: 0 5px;
.photo{
box-shadow: 0px 0px 3px 3px gray;
>img{
width: 160px;
display: block;
}
}
}
}
用js实现,下拉加载
window.addEventListener("load", getHtml)
function getHtml() {
var data = [
{ img: "75.jpg" },
{ img: "74.jpg" },
{ img: "97.jpg" },
{ img: "96.jpg" },
{ img: "95.jpg" },
{ img: "94.jpg" },
{ img: "93.jpg" },
{ img: "92.jpg" },
{ img: "91.jpg" },
{ img: "90.jpg" },
{ img: "89.jpg" },
{ img: "88.jpg" },
{ img: "87.jpg" },
{ img: "86.jpg" },
{ img: "85.jpg" },
{ img: "84.jpg" },
{ img: "83.jpg" },
{ img: "82.jpg" },
{ img: "81.jpg" },
{ img: "80.jpg" },
{ img: "79.jpg" },
{ img: "78.jpg" },
]
var wrapper = document.querySelector("#wrapper");
//滚动条事件
window.onscroll = function () {
//如果总高大于最后一张图的高
if (isok()) {
//循环数据
for (var i in data) {
//写入
wrapper.innerHTML += `<div class="box">
<div class="photo">
<img src="./images/${data[i].img}" alt="">
</div>
</div>`
}
//图片排序
install();
}
}
install()
//封装图片排列顺序
function install() {
var wrapper = document.querySelector("#wrapper");
//html的宽
var html_w = document.documentElement.clientWidth || document.body.clientWidth;
var boxs = document.querySelectorAll(".box");
//其中一个图片的宽
var boxs_w = boxs[0].offsetWidth;
//一排可以放几个图
var cols = Math.floor(html_w / boxs_w);
//重新给wrapper设置宽
wrapper.style.width = boxs_w * cols + "px";
var arr = [];
//循环每一张图片
for (var i = 0; i < boxs.length; i++) {
//下标小于一排能放下的个数
if (i < cols) {
//把这几个图片的高放入空数组
arr.push(boxs[i].offsetHeight);
} else {
//声明一个数组中最小值
var minH = Math.min.apply(Math, arr);
//声明一个下标为最小值的小标
var ind = arr.indexOf(minH);
//给剩余图片定位
boxs[i].style.cssText = `position:absolute;left:${ind * boxs_w}px;top:${minH}px;`
//更新定位后图片的高度
arr[ind] += boxs[i].offsetHeight;
}
}
}
//图片是否加载
function isok() {
var boxs = document.querySelectorAll(".box");
//html的高
var html_h = document.documentElement.clientHeight || document.body.clientHeight;
//总高度 html的高加滚动的高
var z_top = html_h + (document.documentElement.scrollTop || document.body.scrollTop);
//最后一张图片的高度
var last_tu = boxs[boxs.length - 1].offsetHeight + boxs[boxs.length - 1].clientHeight/2;
//返回结果 如果总高度大于最后一张图片的高度就为true
return z_top > last_tu ? true : false;
}
}