1.瀑布流的实现原理:
通过计算出一排能够容纳几列元素,而后找到各列之中所有元素高度之和的最小者,并将新的元素增加到该列上,而后继续寻觅所有列的各元素之和的最小者,继续增加至该列上,如此循环下去,直至所有元素均能够按要求排列为止
2.效果图
瀑布流.png
3.基本思想
- 使用
flex布局,将container划分为等分的4列。 - 对所有的
img设置一个宽度100%,即就是保证这些图的宽度恰好充满整个列。 - 为了美观,我给图片加上了少量
css3特效,淡入淡出以及hover放大
等分4列
图片宽度设置相同
html结构
<body> <div class="container"> <div class="item" id="one"> </div> <div class="item" id="two"> </div> <div class="item" id="three"> </div> <div class="item" id="four"> </div> </div></body>css
body{ margin: 0; padding: 0; background-color: #ededed;}.container{ width: 80%; display: flex; flex-direction: row; margin: 0 auto;}.item{ flex: 1; margin: 16px; transition: all 0.3s ease-in-out;}img{ width: 100%; border: 10px solid white; margin-top: 8px;}img:hover{ transform: scale(1.05); cursor: pointer; box-shadow:0px 3px 2px 1px #999;}接下来就是我的js了
- 动态插入图片
- 给浏览器时间渲染,也就是设置定时器
- 寻觅最低的列
var endScroll=window.screen.height+500;//预期结束的位置//加载页面window.onload=function(){ var canScroll=document.documentElement.scrollHeight;//可以滚动的高度 var alreadyScorll=document.documentElement.scrollTop; insertImg(); window.document.addEventListener('scroll',function(){ if(alreadyScorll+window.screen.height>canScroll){ endScroll+=500; insertImg(); } });}//动态插入图片var insertImg=function(){ var imgId=0; //设置定时器让浏览器有时间渲染 var timer=setInterval(function(){ var canScroll=document.documentElement.scrollHeight;//可以滚动的高度 if(canScroll>endScroll){ clearInterval(timer); } imgId++; if(imgId>14){ imgId=1;//我的图片只有14张 } var img=document.createElement('img'); img.setAttribute('src','img/'+imgId+'.jpg'); minCOlum().appendChild(img); },100)}//寻觅高度最小的列var minCOlum=function(){ var pb1=document.getElementById('one'); var pb2=document.getElementById('two'); var pb3=document.getElementById('three'); var pb4=document.getElementById('four'); var pb1Height=cuculate(pb1.children); var pb2Height=cuculate(pb2.children); var pb3Height=cuculate(pb3.children); var pb4Height=cuculate(pb4.children); var minHeight=Math.min(pb1Height,pb2Height,pb3Height,pb4Height); if(minHeight==pb1Height){ return pb1; }else if(minHeight==pb2Height){ return pb2; }else if(minHeight==pb3Height){ return pb3; }else{ return pb4; }}//计算最小高度的列var cuculate=function(pbimg){ if(pbimg==null||pbimg.length==0){ return 0; }else{ var height=0; for(var i=0;i<pbimg.length;i++){ height+=pbimg[i].height; } return height; }}
最后再附上效果图
好了,瀑布流布局今天就先到这里啦