JQuery实现瀑布流布局
瀑布流布局:
1、图片等宽不等高
2、定义规定列数,从第二行开始,图片插入高度最小的列中,依次类推
3、图片的父元素设置相对定位,图片元素设置绝对定位
index.html
<head>
<meta charset="UTF-8">
<title>JQuery---瀑布流布局</title>
<style> * {
margin: 0; padding: 0; } .div_main {
width: 100%; position: relative; } div {
display: block; } .div_img {
padding: 12px; float: left; } .div_img img {
width: 410px; border: 1px solid #dddddd; } </style>
<script type="text/javascript" src="./jQuery/jquery.min.js"></script>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div class="div_main">
<div class="div_img">
<img src="./image/1.jpg" alt="">
</div>
<div class="div_img">
<img src="./image/2.jpg" alt="">
</div>
<div class="div_img">
<img src="./image/3.jpg" alt="">
</div>
<div class="div_img">
<img src="./image/4.jpg" alt="">
</div>
<div class="div_img">
<img src="./image/5.jpg" alt="">
</div>
<div class="div_img">
<img src="./image/6.jpg" alt="">
</div>
<div class="div_img">
<img src="./image/7.jpg" alt="">
</div>
<div class="div_img">
<img src="./image/8.jpg" alt="">
</div>
<div class="div_img">
<img src="./image/9.jpg" alt="">
</div>
<div class="div_img">
<img src="./image/10.jpg" alt="">
</div>
<div class="div_img">
<img src="./image/11.jpg" alt="">
</div>
<div class="div_img">
<img src="./image/12.jpg" alt="">
</div>
<div class="div_img">
<img src="./image/13.jpg" alt="">
</div>
<div class="div_img">
<img src="./image/14.jpg" alt="">
</div>
<div class="div_img">
<img src="./image/15.jpg" alt="">
</div>
<div class="div_img">
<img src="./image/16.jpg" alt="">
</div>
</div>
</body>
index.js
$(window).on('load',function () {
waterFall()
});
function waterFall() {
var div = $(".div_img");
var divWidth = div.outerWidth();//当前图片的宽度
var screenWidth = $(window).width();//整个屏幕的宽度
//求出列数
var cols = parseInt(screenWidth/divWidth);
//定义高度数组
var heightArray = [];
//判断哪个高度最小,往下面添加图片
$.each(div, function (index, item) {
//获取图片高度
var divHeight = $(item).outerHeight();
//如果当前还是一行的话
if(index < cols){
heightArray[index] = divHeight;
}
//否则
else {
//遍历每一列的高度
// 返回最小值
var minBoxHeight = Math.min(...heightArray);
// 同上
// var min = heightArray[0];
// for( var i=1; i<heightArray.length;i++){
// if(heightArray[i]<min){
// min=heightArray[i];//求出最小的高度值
// }
// }
//返回规定值的id
var minBoxIndex = $.inArray(minBoxHeight, heightArray);
// 改变最小index的高度
$(item).css({
position:"absolute",
left: minBoxIndex * divWidth + "px",
top: minBoxHeight+"px"
});
// 数组高度追加
heightArray[minBoxIndex] += divHeight;
}
});
}
结果显示:
备注:
有参考和借鉴,若侵权,联系可删