# 前端基础(通过 js 来实现瀑布流)

html 的代码块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<div style="height:50px">瀑布流 </div>
<div style="height:60px">瀑布流 </div>
<div style="height:70px">瀑布流 </div>
<div style="height:60px">瀑布流</div>
<div style="height:50px">瀑布流</div>
<div style="height:50px">瀑布流</div>
<div style="height:70px">瀑布流</div>
<div style="height:50px">瀑布流</div>
<div style="height:80px">瀑布流</div>
<div style="height:50px">瀑布流 </div>
<div style="height:40px">瀑布流 </div>
<div style="height:60px">瀑布流 </div>
<div style="height:50px">瀑布流 </div>
<div style="height:70px">瀑布流 </div>
<div style="height:50px">瀑布流 </div>
<div style="height:70px">瀑布流 </div>
<div style="height:50px">瀑布流 </div>
<div style="height:50px">瀑布流 </div>
<div style="height:70px">瀑布流 </div>
<div style="height:50px">瀑布流 </div>
<div style="height:80px">瀑布流</div>

css 部分的代码块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<style>
* {
margin: 0px;
padding: 0px;
}
div {
width: 150px;
position: absolute;
border: 1px solid;
}
img {
display: inline-block;
width: 150px;
}
#wrap {
position: relative;
width: 100%;
}
</style>

js 的代码块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<script>
var div = document.getElementsByTagName("div");
//因为图片较多,在加载时,就加载图片
window.onload = function(){
Full();
}
//当窗口大小改变时,重新分列并排序
window.onresize = function(){
Full();
}
//瀑布流函数
function Full(){
//求分几列
var pw = document.documentElement.offsetWidth; //页面宽度
var dw = div[0].offsetWidth; //每个div宽度
var cols = Math.floor(pw/dw);
//缝隙数等于列数加1,例如6行有7个缝隙
var white = (pw - dw * cols)/(cols + 1);
//每一列定位
var t = 10;
var arr = [];
for(var i = 0;i<cols;i++){
var pos = {
//计算每个div的坐标(开始让每个top取一个固定值)
//横坐标每次不变,只有top变
/*
div[0] left: white
div[1] left: white*2 + dw
div[2] left: white*3 + dw*2
*/
x:Math.floor((i+1)*white+dw*i),
y:t
}
arr.push(pos); //将坐标存入数组
}
console.log(arr);
//每次找高度最小的一列
for(var j = 0;j<div.length;j++){
var index = getMinTop(arr);
div[j].style.left = arr[index].x + "px";
div[j].style.top = arr[index].y + "px";
arr[index].y += div[j].offsetHeight + t;
console.log("arr[index]",arr[index]);
}
}
//求每次最小高度的列
function getMinTop(arr){
var minT = arr[0].y;weizhi
var index = 0;
for(var k = 0;k<arr.length;k++){
if(arr[k].y < minT){
minT = arr[k].y;
index = k;
}
}
return index;
}
</script>

我时通过 js 来计算出每一列的个数,留白部分可以写死。通过绝对定位(top 和 left)来个基本的 css 属性值来控制位置,通过 * getMinTop(arr)* 来实现对每一列遍历循环插入 div,绝对高度最小的插入 div。这个就是瀑布流的实现原理。