Javascript瀑布流布局

Javascript瀑布流布局

因为在许多app还有图片软件看见这种参差不齐的效果有点好奇所以百度看了一下如何实现,有些人使用css3的栅格化布局实现。我这次学习的是使用js实现瀑布流布局

思路

计算每一列项目高度

对比每一项找到最小一项

把图片动态的插入到最小一项上

再次计算图片高度进行插值

效果图

基本Html

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
<!DOCTYPE html>
<html>
<head>
<title>template</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div class="container">
<div class="item" id="line1">
<img src="img/1.jpg">
<img src="img/3.jpg">
<img src="img/4.jpg">
</div>
<div class="item" id="line2">
<img src="img/2.jpg">
<img src="img/5.jpg">
<img src="img/6.jpg">
</div>
<div class="item" id="line3">
<img src="img/9.jpg">
<img src="img/10.jpg">
</div>
<div class="item" id="line4">
<img src="img/3.jpg">
<img src="img/2.jpg">
<img src="img/5.jpg">
</div>
</div>
</body>
<script src="index.js"></script>
</html>

img标签只是为了初步展示数据完成后可以删除

找到最小值项目

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
var mindDiv = ()=>{

let [line1,line2,line3,line4] = [
document.getElementById('line1'),
document.getElementById('line2'),
document.getElementById('line3'),
document.getElementById('line4')]
let [lineImg_1,lineImg_2,lineImg_3,lineImg_4] = [
line1.children,
line2.children,
line3.children,
line4.children]
let [lineHeight1,lineHeight2,lineHeight3,lineHeight4] = [
computer(lineImg_1),
computer(lineImg_2),
computer(lineImg_3),
computer(lineImg_4)]

let minHeight = Math.min(lineHeight1,lineHeight2,lineHeight3,lineHeight4)

if (minHeight == lineHeight1) {
return line1
}
if (minHeight == lineHeight2) {
return line2
}
if (minHeight == lineHeight3) {
return line3
}
if (minHeight == lineHeight4) {
return line4
}

}

使用了ES6的数组的解构赋值 具体文档http://caibaojian.com/es6/destructuring.html

计算项目高度

1
2
3
4
5
6
7
8
9
10
11
12
13
var computer =(lineImg)=>{
if (lineImg == null || lineImg.length == 0) {
return 0;
}else{
var height = 0;
for(var i = 0; i < lineImg.length; i++){
var img = lineImg[i];
var h = img.height;
height += h;
}
return height
}
}

插值

监听窗口变化超过设定高度就再次执行加载

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
window.onload = ()=>{
insertImg();
window.document.addEventListener('scroll',function(){
if (document.documentElement.scrollTop + window.screen.height > document.documentElement.scrollHeight) {
windowHeight += 500;
insertImg()
}
})

}

var insertImg = ()=>{
var inter = setInterval(function(){
if (document.documentElement.scrollHeight > windowHeight) {
clearInterval(inter)
}
var mDiv = mindDiv();
imgId ++;
if (imgId > 10) {
imgId = 1;
}
var img = document.createElement('img')
img.setAttribute("src","img/" + imgId + ".jpg")
mDiv.appendChild(img);
},100)
}