只放了js部分,剛希望多多指出錯誤
window.onload=function(){
//實現瀑布流布局
waterfall('main','box');//調用
//鼠標滾動加載圖片
window.onscroll=function (){
if (cheakwillloadnewimage()){
//數據
vardataarr=[{src:'20.jpg'},
{src:'20.jpg'},
{src:'22.jpg'},
{src:'23.jpg'},
{src:'24.jpg'},
{src:'25.jpg'},
{src:'26.jpg'},
]
//遍歷數組,插入新的標簽
for (vari=0;i
varnewbox=document.createElement('div')
newbox.className='box';
$('main').appendChild(newbox);
varpics=document.createElement('div');
pics.className='pic';
newbox.appendChild(pics);
varimgs=document.createElement('img');
imgs.src='images/'+dataarr[i].src;
pics.appendChild(imgs);
}
waterfall('main','box');//重新調用布局
}
}
//函數
functionwaterfall(parent,box){
//讓父盒子居中
//獲取所有盒子
varallbox= $('main').getElementsByClassName(box);
//獲取盒子寬度
varboxwidth=allbox[0].offsetWidth;
//獲取屏幕寬度
varscreenwidth=document.documentElement.clientWidth;
//算出一共多少列
varrole=parseInt(screenwidth/boxwidth);
//console.log(role);
//居中
$('main').style.width=role*boxwidth+'px';
$('main').style.margin='0 auto';
//子盒子居中
//定義高度數組
varheightarr=[];
//遍歷數組
for (vari=0;i
//盒子的高度
varboxheight=allbox[i].offsetHeight;
//console.log(boxheight);
//取出第一行盒子的高度并且放進數組
if (i
heightarr.push(boxheight);
}else{//剩余行
//求出數組中最矮的盒子高度
varminheight= _.min(heightarr);
//console.log(minheight); 146
//求出最矮盒子對應的下標索引
varminboxindex=getMinBoxIndex(heightarr,minheight);
//console.log(minboxindex);
//子盒子定位(定在最小盒子下面)
allbox[i].style.position='absolute';
allbox[i].style.left=minboxindex*boxwidth+'px';
allbox[i].style.top=minheight+'px';
//更新數組
heightarr[minboxindex]+=boxheight;
}
}
//console.log(heightarr);
}
//求出最矮盒子對應的下標
functiongetMinBoxIndex(arr,val){
for (vari=0;i
if (arr[i]==val){
returni;
}
}
}
//判斷是否加載新圖片
//返回值true false
functioncheakwillloadnewimage(){
//獲取最后一個盒子
varallbox=document.getElementsByClassName('box');
//console.log(allbox.length)
varlastbox=allbox[allbox.length-1];
//計算最后一個盒子偏離網頁的距離以及自身高度的一半
varlastboxt=lastbox.offsetHeight*0.5+lastbox.offsetTop;
//console.log(lastboxt);
//求出屏幕高度
varscreenh=document.documentElement.clientHeight||document.body.clientHeight;
//console.log(screenh)
//求出被網頁卷出去的距離
varscrollt=scroll().top;
//console.log(scrollt)
returnlastboxt<=screenh+scrollt;
//console.log(lastboxt, screenh, scrollt);
}
}