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_阅读 661评论 0 0
  • html结构 (Emmet)(div.box>div.pic>img[src="images/$.jpg"])*2...
    黎贝卡beka阅读 529评论 1 4
  • 1、什么是教学服务?你的理解是什么? 1)定义:教师用自己的专业和责任赢取客户信任的课堂外服务。2)我的理解:在课...
    陈超见阅读 185评论 1 0
  • 第六天 6月17日 雨天 今天给老爸老妈视频电话了,虽然没说什么特别的,但是聊聊家常,似乎也会得到满足,鼓...
    活石美音阅读 224评论 2 2