原生js实现瀑布流效果
参考此篇:https://segmentfault.com/a/1190000012621936
以下为个人测试中:
css:
.masonry{
width:100%;
}
.item{
position: absolute;
}
img{
width: 100%;
}
.gap{
width: 20px;
}
html:
<div class="masonrybox">
<div class="masonry">
<div class="item">
<img class="lazy" src="http://img3.imgtn.bdimg.com/it/u=3820866398,3484834793&fm=26&gp=0.jpg" alt="" />
</div>
<div class="gap"></div>
<div class="item">
<img class="lazy" src="http://img0.imgtn.bdimg.com/it/u=612897915,2145385515&fm=26&gp=0.jpg" alt="" />
</div>
<div class="gap"></div>
<div class="item">
<img class="lazy" src="http://img1.imgtn.bdimg.com/it/u=963830906,168991667&fm=26&gp=0.jpg" alt="" />
</div>
<div class="item">
<img class="lazy" src="http://img3.imgtn.bdimg.com/it/u=3745098494,888696443&fm=26&gp=0.jpg" alt="" />
</div>
<div class="gap"></div>
<div class="item">
<img class="lazy" src="http://img3.imgtn.bdimg.com/it/u=2142147217,643937300&fm=26&gp=0.jpg" alt="">
</div>
<div class="gap"></div>
<div class="item">
<img class="lazy" src="http://img0.imgtn.bdimg.com/it/u=2766297745,3964264989&fm=26&gp=0.jpg" alt="" />
</div>
<div class="gap"></div>
<div class="item">
<img class="lazy" src="http://img3.imgtn.bdimg.com/it/u=2941108349,3865760420&fm=26&gp=0.jpg" alt="" />
</div>
</div>
</div>
<script>
var scrrenWidth = $(".masonry").width();
var iw = (scrrenWidth-40)/3;
$(".item").css("width",iw);
function getCurrent(){
var min = Math.min.apply(null, arr);
$.each(arr,function(i){
if(arr[i] == min){
index = i;
console.log(arr[i]);
return false;
}
})
}
var index = 0;
var arr = [];
var w = 0;
var leftNum = 0;
$.each($(".item"),function(i){
w = $(this).width();
if(i<3){
leftNum = ($(".gap").width()+w)*i;
arr.push( $(this).height());
}else{
getCurrent();
leftNum = ($(".gap").width()+w)*index;
$(this).css("top",arr[index]+10);
arr[index]+= $(this).height()+10;
}
$(this).css("left",leftNum);
})
</script>