原理:
使用 wx.createSelectorQuery()来动态获取元素的高度信息,来动态分配到左边还是右边
- 首先定义两个变量,再循环一下你要处理的数组,这里使用async await的目的是让上一次数据处理完成后再进行下一次循环,以免造成不必要的麻烦
//分别定义左右两边的高度,写在页面的最上面
let leftHeight = 0,rightHeight = 0;
for (const item of value) {
await this.getBoxHeight(item);
}
// 数据处理
getBoxHeight(item) {
// 接受一个对象
return new Promise((resolve, reject) => {
// 当左边元素的高度小于等于右边的元素高度时
// 往left数组里添加这个对象
if(leftHeight <= rightHeight){
this.setData({
left : this.data.left.concat([item])
}, () => {
// 这里是setData完成的回调
// 此时元素已经渲染到页面上
// 使用wx.createSelectorQuery()来重新获取一下更新之后元素的高度,并赋值到leftHeight或者rightHeight中
// 非自定义组件 请把 in(this) 去掉 自定义组件 需要加上
const query = wx.createSelectorQuery().in(this)
query.select('#left').boundingClientRect();
query.exec((res) => {
if (res[0]) {
leftHeight = res[0].height; //获取左边列表的高度
}
resolve();
});
})
}else{
this.setData({
right : this.data.right.concat([item])
}, () => {
const query = wx.createSelectorQuery().in(this)
query.select('#right').boundingClientRect();
query.exec((res) => {
if (res[0]) {
rightHeight = res[0].height; //获取右边列表的高度
}
resolve();
});
})
}
})
这里是我的页面结构
<import src="../../template/newSuggest_list/newSuggest_list.wxml" />
<view class="flex-r" style="margin-top:20rpx;width:750rpx;overflow:hidden;">
<view class="flex-c">
<view class="flex-c" id="left">
<view class="itemBox animated07s fadeInUp" wx:for="{{left}}" style="{{from=='home'?'margin-right:20rpx;':'margin-left:20rpx;'}}">
<template is="newSuggest_list" data="{{item,index}}"></template>
</view>
</view>
</view>
<view class="flex-c">
<view class="flex-c" id="right">
<view class="itemBox animated07s fadeInUp" wx:for="{{right}}">
<template is="newSuggest_list" data="{{item,index}}"></template>
</view>
</view>
<view style="clear:both;"></view>
</view>
</view>
参考链接 https://blog.csdn.net/qq_37034928/article/details/106097313