web前端工程师学院Web前端之路前端类

JavaScript实现瀑布流效果

2016-12-14  本文已影响107人  grin_sun

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

}

}

上一篇下一篇

猜你喜欢

热点阅读