<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>瀑布流</title>
<!--<link rel="stylesheet" href="index.css">-->
<style>
.box{
150px;
padding: 5px;
float: left;
transition: all 600ms;
}
.box_img{padding: 5px;}
img{
100%;
border-radius: 10px;
box-shadow: 0 0 3px 3px rgba(0,0,0,0.3);
}
</style>
</head>
<body>
<!--<div class="box">
<div class="box_img">
<img src="img/1.jpg">
</div>
</div> -->
</body>
</html>
<script>
//图片名称
var imgs=["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg"
,"6.jpg","7.jpg","8.jpg","9.jpg","10.jpg","11.jpg","12.jpg"
,"13.jpg","14.jpg","15.jpg","16.jpg","17.jpg",
"18.jpg","19.jpg","20.jpg"];
//获取所有BOX
var boxlist=document.getElementsByClassName('box');
/**
* 加载BOX
*/
var st="";
//创建box的三层结构
function loadimg(){
for(var i=0;i<imgs.length;i++){
st+="<div class='box'>"
st+="<div class='box_img'>"
st+="<img src='./img/"+imgs[i]+"'/>"
st+="</div>"
st+="</div>"
}
document.body.innerHTML=st
}
loadimg()
function orderimg(){
// 判断第一行可以放多少张图
var winwidth=document.documentElement.clientWidth||document.body.clientWidth;
var boxwidth=boxlist[0].offsetWidth;
// console.log(boxwidth)
var count=parseInt(winwidth/boxwidth)
console.log(count)
// count就是第一行的图片的个数
// 找出第一行中的所有高,并存起来
var heights=[]
for(var i=0;i<boxlist.length;i++){
if(i<count){
heights.push(boxlist[i].offsetHeight)
boxlist[i].style.position="static"
}else{
// 当我排第五张时找出第一排的最小高对应的元素
var minheight=Math.min.apply(null,heights);
// 找最小高对应的索引
var indexj=null;
for(var j in heights){
if(heights[j]==minheight){
indexj=j
}
}
// 找出索引对应的那个元素
var minbox=boxlist[indexj];
// 排第五张图片的位置
boxlist[i].style.position="absolute";
boxlist[i].style.left=minbox.offsetLeft+"px";
boxlist[i].style.top=minheight+"px"
heights[indexj]=minheight+boxlist[i].offsetHeight;
}
}
console.log(heights,minheight,indexj)
}
window.onload=function(){
orderimg()
}
window.onscroll=function(){
var endbox=boxlist[boxlist.length-1].offsetTop;
var w=document.documentElement.scrollTop||document.body.scrollTop;
var wd=document.documentElement.clientHeight||document.body.clientHeight;
if(w+wd>endbox){
loadimg()
orderimg()
}
}
window.onresize=function(){
orderimg()
}
</script>