1. 实现思路
设置好卡片占据屏幕的宽度的50%,使之实现两列卡片。将父盒子设置相对定位, 子元素设置为绝对定位,并且设置top 和left 为参数变量。 在onload 中获取子元素的高度,通过判断高度大小来排布卡片排列位置。
2.实现过程
2.1 遍历数据,并且设置top 和left 为参数变量,图片设置为宽度自适应。
2.2 获取所有item的高度
2.3 循环判断高度大小并给top和left赋值,并且累加该子元素所在位置的高度。
3. 代码展示
<template>
<view class="container">
<view class="box">
<view v-for="(item,index) in list " class="item" :style="{'--top2':item.top+'px','--left':item.left}">
<image :src="item.url" mode="widthFix"></image>{{index}}
</view>
</view>
</view>
</template>
<script setup>
import {
ref
} from 'vue';
import {
onLoad
} from "@dcloudio/uni-app";
// 图片高度的数组
const AllData = ref([]);
// 图片左边距离顶部的高度
const leftHeight = ref(0);
// 图片右边距离顶部的高度
const rightHeight = ref(0);
// 遍历卡片数组
const list = ref([{
url: "../../static/logo.png",
left: "0",
top: "0",
float: "left"
}, {
url: "../../static/1111.png",
left: "50%",
top: "0",
float: "right"
}, {
url: "../../static/2222.png",
left: "0",
top: "0",
float: "left"
},
{
url: "../../static/logo.png",
left: "50%",
top: "900",
},
{
url: "../../static/1111.png",
left: "50%",
top: "900",
},
{
url: "../../static/logo.png",
left: "50%",
top: "900",
},
{
url: "../../static/logo.png",
left: "50%",
top: "900",
},
{
url: "../../static/2222.png",
left: "50%",
top: "900",
},
{
url: "../../static/1111.png",
left: "50%",
top: "900",
},
{
url: "../../static/logo.png",
left: "50%",
top: "900",
},
])
onLoad(() => {
setTimeout(() => {
// 获取卡片元素的数据
uni.createSelectorQuery().selectAll('.item').boundingClientRect(data => {
console.log("打印所有数据", data)
// 截取单独高度数据
data.forEach((item) => {
AllData.value.push(item.height);
})
console.log("打印所有数据", AllData.value);
// 遍历高度数组
for (let i = 0; i < AllData.value.length; i++) {
// 判断赋值
if (rightHeight.value < leftHeight.value ) {
// 设置位置
list.value[[i]].left = '50%';
// 先进行赋值
list.value[i].top = rightHeight.value;
// 再进行累加
rightHeight.value += AllData.value[i];
} else {
list.value[i].left = 0;
list.value[i].top = leftHeight.value;
leftHeight.value += AllData.value[i];
}
}
}).exec()
}, 1000)
})
</script>
<style lang="scss" scoped>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 100%;
height: 100%;
.box {
width: 100%;
height: 100%;
position: relative;
.item {
width: 50%;
display: inline-block;
border: 1px solid #ccc;
box-shadow: 0 0 6px #ccc;
break-inside: avoid;
position: absolute;
// 设置为变量
top: var(--top2);
left: var(--left);
image {
width: 100%;
}
}
}
}
</style>
4.实现效果