<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
padding: 0;
margin: 0;
}
.box{
width: 200px;
box-sizing: border-box;
float: left;
}
.box img{
width: 100%;
}
</style>
<script src="../jQuery/jquery-3.4.1.min.js"></script>
</head>
<body>
<div class="boxContent">
<div class='box'><img src="../img/1.jpg" alt="" srcset=""></div>
<div class='box'><img src="../img/2.jpg" alt="" srcset=""></div>
<div class='box'><img src="../img/3.jpg" alt="" srcset=""></div>
<div class='box'><img src="../img/4.jpg" alt="" srcset=""></div>
<div class='box'><img src="../img/5.jpg" alt="" srcset=""></div>
<div class='box'><img src="../img/woga1.jpg" alt="" srcset=""></div>
<div class='box'><img src="../img/woga2.jpg" alt="" srcset=""></div>
<div class='box'><img src="../img/woga3.jpg" alt="" srcset=""></div>
<div class='box'><img src="../img/woga4.jpg" alt="" srcset=""></div>
<div class='box'><img src="../img/woga5.jpg" alt="" srcset=""></div>
</div>
<script>
var box=$('.box'); // 求出所有存储图片的 div标签集合
var boxWidth=box.width(); // 得到每个div的宽度 其实也是图片的宽度
var screenWidth=$(window).width(); // 得到屏幕的宽度
var cols=parseInt(screenWidth/boxWidth) ; // 求出第一行显示图片的个数
var heightArr=[]; // 用来存储 第一行每个图片高度的数组
// 图片遍历循环 除了第一排不需要定位 取高度值 其他排定位处理
$.each(box,function(index,item){
var boxHeight=$(item).outerHeight(); // 求出每张图片的高度
if(index<cols){
// 算出第一行所有图片的高度
heightArr[index]=boxHeight; // 放入到数组中
}else{
// 第二行的 图片 放入的位置取决于那张图片高度最小
var minHeightBox=Math.min(...heightArr);// 高度最小的图片
var minBoxIndex=$.inArray(minHeightBox,heightArr);//高度最小的图片的索引
$(item).css({
position:'absolute',
left:minBoxIndex*boxWidth+'px',
top:minHeightBox+'px'
})
// 高度追加
heightArr[minBoxIndex]+=boxHeight;
}
})
</script>
</body>
</html>
<!-- 还有一种就是使用弹性布局来解决
flex 实现瀑布流需要将最外层元素设置为 display: flex,即横向排列。
然后通过设置 flex-flow:column wrap 使其换行。设置 height: 100vh 填充屏幕的高度,来容纳子元素
// 复习一下flex-flow 的样式 使用
flex-flow 属性是 flex-direction 和 flex-wrap 属性的复合属性。
flex-flow 属性用于设置或检索弹性盒模型对象的子元素排列方式。
flex-direction 属性规定灵活项目的方向。
flex-wrap 属性规定灵活项目是否拆行或拆列。
.boxContent {
display: flex;
flex-flow:column wrap;
height: 100vh;
}
.box {
width: 200px;
}
.box img{
width: 100%;
} -->
前端经典瀑布流布局jquery实现
猜你喜欢
转载自blog.csdn.net/qq_42526440/article/details/113953694
今日推荐
周排行