<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>瀑布流</title>
</head>
<style>
.waterfall{
width: 100%;
height: auto;
border: 1px red solid;
position: relative;
}
.waterfall img{
width: 400px;
border: 1px red solid;
display: block;
position: absolute;
margin:5px;
}
</style>
<body>
<div class="waterfall">
<img src="./img/t1.png" alt="1">
<img src="./img/t2.png" alt="2">
<img src="./img/t3.png" alt="3">
<img src="./img/t4.png" alt="4">
<img src="./img/t5.png" alt="5">
<img src="./img/t6.png" alt="6">
<img src="./img/t7.png" alt="7">
</div>
<script src="js/jquery.3.4.1.js"></script>
<script>
var imgWidth = $('.waterfall img').outerWidth(true) //单张图片的宽度
//当窗口大小重置之后,重新执行
$(window).on('resize',function(){
reset()
})
//当窗口加载完毕,执行瀑布流
$(window).on('load',function(){
reset()
})
//定义reset函数
function reset(){
var colHeightArry= []
colCount = parseInt($('.waterfall').width()/imgWidth)
for(var i = 0 ; i < colCount; i ++){
colHeightArry[i] = 0
}
$('.waterfall img').each(function(){
var minValue = colHeightArry[0]
var minIndex = 0
for(var i = 0 ; i < colCount; i ++){
if(colHeightArry[i] < minValue){
minValue = colHeightArry[i]
minIndex = i
}
}
$(this).css({
left: minIndex * imgWidth,
top: minValue
})
colHeightArry[minIndex] += $(this).outerHeight(true)
})
}
</script>
</body>
</html>
网友评论