每天一点scc js实现瀑布流
程序员文章站
2022-05-01 21:54:19
...
瀑布流
总的来说就是求出div的高度,让它插入最小的。
效果大概使这个样子的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
body{
background: #cccccc50;
}
.container{
width: 70%;
margin: 0 auto;
display: flex;
flex-direction: row;
}
.container > .item{
flex:1 /*弹性项的占比*/;
margin: 17px;
}
.container> .item>img{
width:100%;
border: 10px solid white;
margin-top: 8px;
transition:all 0.3s ease-in-out;
}
.container > .item > img:hover{
cursor: pointer;
transform: scale(1.05);/*变大1.1倍*/
box-shadow: 0 3px 2px 1px #999;
}
</style>
<script>
//屏幕默认大小,初始化图片的占用位置
let windowHeight = window.screen.height+500;
let imgId = 0;
window.onload = function(){
insertImg();
//监听滚动事件
window.document.addEventListener("scroll", function(){
if(document.documentElement.scrollTop+ window.screen.height > document.documentElement.scrollHeight){
//再此插入图片
windowHeight+=500;
insertImg();
}
});
};
let insertImg = function(){
let inter = setInterval(function () {
if(document.documentElement.scrollHeight>windowHeight){
clearInterval(inter)
}
let mDiv = minDiv();
imgId++;
if(imgId>6){
imgId=1;
}
let img =document.createElement("img");
img.setAttribute("src","img/"+"0"+imgId+".jpg");
mDiv.appendChild(img)
},100)
};
let minDiv = function(){
let pd1 = document.getElementById("pd-01");
let pd2 = document.getElementById("pd-02");
let pd3 = document.getElementById("pd-03");
let pd4 = document.getElementById("pd-04");
let pd1_img = pd1.children;
let pd2_img = pd2.children;
let pd3_img = pd3.children;
let pd4_img = pd4.children;
let pd1Heigth = sun(pd1_img);
let pd2Heigth = sun(pd2_img);
let pd3Heigth = sun(pd3_img);
let pd4Heigth = sun(pd4_img);
let minLength =Math.min(pd1Heigth,pd2Heigth,pd3Heigth,pd4Heigth);
if (minLength === pd1Heigth){
return pd1;
}
if (minLength === pd2Heigth){
return pd2;
}
if (minLength === pd3Heigth){
return pd3;
}
if (minLength === pd4Heigth){
return pd4;
}
};
let sun =function (pd) {
if (pd == null || pd.length === 0){
return 0;
}else {
let height = 0;
for (let i = 0; i < pd.length; i++) {
let img = pd[i];
let h = img.height;
height +=h;
}
return height;
}
};
</script>
</head>
<body>
<div class="container">
<div class="item" id = "pd-01">
</div>
<div class="item" id = "pd-02">
</div>
<div class="item" id = "pd-03">
</div>
<div class="item" id = "pd-04">
</div>
</div>
</body>
</html>
-img.setAttribute("src","img/"+"0"+imgId+".jpg");
这个使用字符串拼接的