需求:
瀑布流排序非等长的块级
一排两个样式图如下:
(先直接讲解决方案,后续放原生3种方式的缺点,有兴趣往后看)
解决方案:
使用 Macy.js
插件
官网:http://macyjs.com/
优点:
- 体积小,仅4KB
- 无需依赖
jQuery
- 可配置化强,一句话可解决瀑布流显示
Code:
JS使用
// react Hook中的使用
useEffect(() => {
// 瀑布流设置
var masonry = new Macy({
container: '#mainList', // 图像列表容器id
trueOrder: true, // 不设置的话会顺序会乱
waitForImages: false,
useOwnImageLoader: false,
debug: true,
//设计间距
//设置列数
columns: 2,
//定义不同分辨率(1200,940,520,400这些是分辨率)
breakAt: {
1200: {
columns: 5,
margin: 10,
},
940: {
columns: 4,
margin: 10,
},
520: {
columns: 3,
margin: 8,
},
400: {
margin: 8,
columns: 2,
},
},
});
}, []);
页面代码:
return (
<div className={styles.recomandList} id="mainList">
{data.map((item) => {
return (
<div className={styles.recomandItem} key={item.id}>
item 代码
</div>
);
})}
</div>
);
以上即可实现需求中的瀑布流样式
更多使用可参考此博文:https://www.shejidaren.com/macy-js-plugin.html
原生css编写瀑布流的三种方式分析
在上一篇博文可看:https://blog.csdn.net/qq_40593656/article/details/116986759