开门见山,本文介绍响应式的瀑布流的实现方法。
最终效果图如下,改变浏览器大小效果更棒哦~
![b3f9287a3314913e5cbde38ffe004cca.png](https://i-blog.csdnimg.cn/blog_migrate/1d32d8056893801259d35a52d6738233.jpeg)
以下我们将每个瀑布流盒子简称为box
使用数组记录每个box宽和高
设置不同屏幕宽度下每一行box的数量
1
2
3
4
5
6
|
var num = 4; //每行box数量
if ($(window).width() <= 500) num = 1;
if ($(window).width() > 500) num = 2;
if ($(window).width() > 800) num = 3;
if ($(window).width() > 1200) num = 5;
var boxWidth = $(window).width() / num; //每个box宽度
|
创建数组对象
1
2
3
4
5
6
7
|
function boxStyle(width, height, top, left) {
this.position = "absolute";
this.width = width;
this.height = height;
this.top = top;
this.left = left;
}
|
创建数组记录元素宽高
这里简述一下瀑布流原理:第一行box从左往右排列,第二行开始box的添加位置为各列中高度最小的一列,添加后该列高度则加上该box高度,以此类推
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
box.each(function(index, value) {
//设置每个元素宽度,高度自定义auto
$(value).css({
"width": boxWidth,
"height": "auto"
});
//数组boxStyleArr保存每个元素宽高
boxStyleArr[index] = new boxStyle();
boxStyleArr[index].width = boxWidth;
boxStyleArr[index].height = box.eq(index).height();
//首行box从左到右依次排列
if (index < num) {
boxArr[index] = boxStyleArr[index].height;
boxStyleArr[index].left = boxWidth * index;
boxStyleArr[index].top = 0;
//瀑布流原理计算每个box的位置(left和top)
} else {
var minboxHeight = Math.min.apply(null, boxArr);
var minboxIndex = $.inArray(minboxHeight, boxArr);
boxStyleArr[index].left = boxStyleArr[minboxIndex].left;
boxStyleArr[index].top = minboxHeight;
boxArr[minboxIndex] += boxStyleArr[index].height;
}
});
|
放置box
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
function boxLocation() {
var box = $(".response");
var boxStyleArr = [];
boxArrBuild(boxStyleArr);
box.each(function(index, value) {
//设置每个box最初位置为左上角,宽高为0
$(value).css({
"position": "absolute",
"top": 0,
"left": 0,
"width": 0,
"height": 0
});
//动画效果使box们进行伸展
$(value).animate({
top: boxStyleArr[index].top,
left: boxStyleArr[index].left,
height: boxStyleArr[index].height,
width: boxStyleArr[index].width
}, 500);
});
}
|
绑定屏幕宽度改变事件
当屏幕大小改变时,触发重新计算box位置
为了避免浏览器频繁改变宽度,这里增加了个小判断
当屏幕改变后200毫秒内不再改变,才触发重新计算
1
2
3
4
5
6
7
8
9
|
$(window).on("load", function() {
boxLocation();
window.onresize = function() {
windowWidth = $(window).width();
if (interval == null) {
interval = setInterval("test()", 200);
}
}
});
|
待完善的地方
考虑图片加载
图片加载过程可能影响对box高度判断
可通过img.load来确保图片加载完成或者失败之后才进行计算
代码优化&封装
尽情发挥你的创造力吧
结束语
这个效果是我从别人的博客看到的,然后自己用jQuery实现,这也不失为创造的乐趣呢。
文章来源:腾讯工程师王贝珊
![59a410835a38b6fc73b606cc92ec5254.png](https://i-blog.csdnimg.cn/blog_migrate/653264560f17e80832c39e7e6e19b5dd.jpeg)
「人人都会微信小程序实战进阶」限时99元领取!
199元+49元=限时特价99元
上线自己的小程序,抢领百万奖学金
微信官方证书召唤你,腾讯offer等你拿
腾讯大牛手把手实例教学,0基础快速上手小程序
后台回复888即可get!
![4003b9691228f2c40f0c6bee5d5d6562.png](https://i-blog.csdnimg.cn/blog_migrate/099c70f039565eabc347b112579168d2.jpeg)
腾讯NEXT学院
求职干货 | 前辈blog | 前端课程