您的位置:首页 > 其它

瀑布流的实现原理与实例

2017-12-06 10:25 176 查看

一、原理:

          

 计算每一行能够容纳的列数。
 寻找每列之中所有高度之和的最小列
 添加新元素至该列
 循环找,直到结束。

        

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="jquery-3.2.1.min.js"></script>
<style>
div.item {
position: absolute;
width: 200px;
margin: 10px;
transition: all 1s;
}

div#content {
position: relative;
}

.part1 {
background-color: yellow;
height: 200px;
}

.part2 {
background-color: #006ac1;
height: 400px;
}

.part3 {
background-color: blueviolet;
height: 300px;
}
</style>
</head>
<body>
<div id="content">
<div class="item part1">1</div>
<div class="item part2">2</div>
<div class="item part3">3</div>
<div class="item part1">4</div>
<div class="item part1">5</div>
<div class="item part2">6</div>
<div class="item part2">7</div>
<div class="item part3">8</div>
<div class="item part1">9</div>
<div class="item part2">10</div>
<div class="item part2">11</div>
<div class="item part2">12</div>
<div class="item part3">13</div>
<div class="item part3">14</div>
</div>
<script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js";></script>;
<script>
function waterFall() {
var widthNum = parseInt($(window).width() / $(".item").outerWidth(true)),//求列数
allHeight = [];//所有高度,一维数组
for(var i = 0; i < widthNum; i++) {
allHeight.push(0)
}//给每一列的高度设置初始值为0
$(".item").each(function() {
var $cur = $(this),
indx = 0,//设置最小索引值
minAllHeight = allHeight[0];//设置最小高度值
for(var j = 0; j < allHeight.length; j++) {
if(allHeight[j] < minAllHeight) {
minAllHeight = allHeight[j];
indx = j;
}
}
$cur.css({
"left": indx * $cur.outerWidth(true),
"top": minAllHeight
});
allHeight[indx] = minAllHeight + $cur.outerHeight(true);//每一列添加对应高度
})
}
waterFall();
$(window).on("resize", function() {
waterFall()
})//改变浏览器大小,调用函数。
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: