JavaScript實現瀑布流效果

只放了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);

}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 在極客學院下載的js基礎視頻中學習到了用js實現瀑布流效果,然后自己總結了兩個關鍵的點,一個是瀑布流效果的實現,另...
    McRay閱讀 439評論 0 2
  • html結構 (Emmet) (div.box>div.pic>img[src="images/$.jpg"])*...
    LaBaby_閱讀 658評論 0 0
  • html結構 (Emmet)(div.box>div.pic>img[src="images/$.jpg"])*2...
    黎貝卡beka閱讀 529評論 1 4
  • 1、什么是教學服務?你的理解是什么? 1)定義:教師用自己的專業和責任贏取客戶信任的課堂外服務。2)我的理解:在課...
  • 第六天 6月17日 雨天 今天給老爸老媽視頻電話了,雖然沒說什么特別的,但是聊聊家常,似乎也會得到滿足,鼓...
    活石美音閱讀 224評論 2 2