function waterFall(){
var addimg={'data':[{'src':'0.jpg'},{"src":"1.jpg"},{"src":"2.jpg"},{"src":"3.jpg"},{"src":"4.jpg"},{"src":"5.jpg"},{"src":"6.jpg"},{"src":"7.jpg"},{"src":"8.jpg"},{"src":"9.jpg"}]};
var heightArr=[];
screenWidth=window.innerWidth;
columnNum=parseInt(screenWidth/250);
divArr=document.getElementsByTagName("div");
imgArr=[];//图片外的div
var iOfImage=0;
selectChildDiv(imgArr);
for (var i = 0; i < columnNum; i++) {
heightArr.push(imgArr[i].offsetHeight);
}
iOfImage=i;
addColumnHeight(heightArr,imgArr.length,columnNum,imgArr,iOfImage);
iOfImage=imgArr.length;
window.onscroll= function(){
clientH=document.documentElement.clientHeight;//当前窗口高度
scrollH=document.documentElement.scrollTop;//网页被卷进去的高度\
// scrollH =document.documentElement.scrollHeight;//
minLocation=0;
for (var i = 1; i<columnNum; i++) {
if(heightArr[i]<heightArr[minLocation])
minLocation=i;
}
if (heightArr[minLocation]<clientH+scrollH) {
//生成图片节点
ibody=document.getElementsByTagName('body');
for (var i = 0; i < addimg.data.length; i++) {
pdiv=document.createElement('div');
pdiv.className='parent-div';
cdiv=document.createElement('div');
cdiv.className='child-div';
cimg=document.createElement('img');
cimg.src=addimg.data[i].src;
cdiv.appendChild(cimg);
imgArr.push(cdiv);
pdiv.appendChild(cdiv);
ibody[0].appendChild(pdiv);
}
addColumnHeight(heightArr,imgArr.length,columnNum,imgArr,iOfImage);
iOfImage=imgArr.length;
}
};
}
//选择class为child-div的子节点
function selectChildDiv(imgArr){
for (var i = 0; i < divArr.length; i++) {
if (divArr[i].className=="child-div") {
imgArr.push(divArr[i]);
}
}
}
function addColumnHeight(heightArr,imgNum,columnNum,imgArr,iOfImage){ //将图片放入适当位置并更新列高
for (var j = iOfImage; j < imgArr.length; j++) {
minLocation=0;
for (var i = 1; i<columnNum; i++) {
if(heightArr[i]<heightArr[minLocation])
minLocation=i;
}
imgArr[j].style.position='absolute';//设置绝对位移
imgArr[j].style.top=heightArr[minLocation]+'px';
imgArr[j].style.left=minLocation*260+"px";
heightArr[minLocation]+=imgArr[j].offsetHeight;
}
}
初始显示有点点小bug,图片会重叠。后面有空修。