1.瀑布流的实现原理:
通过计算出一排能够容纳几列元素,然后找到各列之中所有元素高度之和的最小者,并将新的元素添加到该列上,然后继续寻找所有列的各元素之和的最小者,继续添加至该列上,如此循环下去,直至所有元素均能够按要求排列为止
2.效果图
3.基本思想
- 使用
flex
布局,将container
划分为等分的4列。 - 对所有的
img
设置一个宽度100%
,即就是保证这些图的宽度刚好充满整个列。 - 为了美观,我给图片加上了一些
css3
特效,淡入淡出以及hover
放大
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;
}
}
好了,瀑布流布局今天就先到这里啦