1、目标效果:
简单瀑布流实现效果,代码在下方,复制便可直接运行,前提是使用uniapp,下方有详细解析!
2、原理:
2.1 css层面
(1).total这个类包裹瀑布流左边部分和瀑布流右边部分,因此它的布局很明显是一行,可以用flex布局也可以用float,但我选择flex布局!瀑布流左右两边存在间隔可以用justify-content: space-between;分开,flex-wrap: wrap;让瀑布流左右两边的元素换行。
(2)瀑布流左边里面的布局是上下的,并且让背景色高度占满父元素的90%,宽度100%
2.2 js层面
(1)如何判断数据在瀑布流左边还是右边?我这边是根据元素在数组中的索引对2取模,如果等于0就在左边,否则在右边
(2)怎么表现出参差不齐的高度?通过数据中的height,动态绑定style来实现的,同理背景色
3、源码
<template>
<view class="total">
<view class="left" v-for="item,index in leftList" :key="index" :style="{height: item.height+'rpx'}">
<!-- 图片 -->
<view class="photo" :style="{ backgroundColor: item.background}">
</view>
<!-- 文字 -->
<text>{
{item.title+index}}</text>
</view>
<view class="right" v-for="item,index in rightList" :key="index" :style="{height: item.height+'rpx'}">
<!-- 图片 -->
<view class="photo" :style="{ backgroundColor: item.background}">
</view>
<!-- 文字 -->
<text>{
{item.title+index}}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
list: [{
title: '标题',
height: 100,
background: 'blue'
}, {
title: '标题',
height: 200,
background: 'black'
}, {
title: '标题',
height: 150,
background: 'red'
}, {
title: '标题',
height: 100,
background: 'green'
}, {
title: '标题',
height: 250,
background: 'yellow'
}, {
title: '标题',
height: 100,
background: 'pink'
},
{
title: '标题',
height: 200,
background: 'blue'
}, {
title: '标题',
height: 200,
background: 'pink'
}, {
title: '标题',
height: 300,
background: 'blue'
},
{
title: '标题',
height: 300,
background: 'orange'
}, {
title: '标题',
height: 200,
background: 'purple'
}
]
}
},
computed: {
leftList() {
let temp = []
this.list.forEach((item, index) => {
if (index % 2 === 0) {
temp.push(item)
}
})
return temp;
},
rightList() {
let temp = []
this.list.forEach((item, index) => {
if (index % 2 !== 0) {
temp.push(item)
}
})
return temp;
}
},
}
</script>
<style lang="less">
.total {
margin: 10rpx auto;
width: 730rpx;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
.left,
.right {
margin-bottom: 20rpx;
width: 350rpx;
display: flex;
flex-direction: column;
}
.left {
border: 1px solid green;
.photo {
width: 100%;
height: 90%;
}
text {
text-align: center;
}
}
.right {
border: 1px solid red;
.photo {
width: 100%;
height: 90%;
}
text {
text-align: center;
}
}
}
</style>