小程序中获取元素使用swan.createSelectorQuery().selectAll('.leftwrapper,.rightwrapper').boundingClientRect(function (rect) {}).exec();
获取某一元素使用select,获取多个元素使用selectAll方法
获取元素方法和setdata都为异步加载 所以循环的时候不能再createSelectorQuery()方法外面添加循环,数据不能及时更新影响结果
leftList: [], rightList: [],leftHight: 0,rightHight: 0
瀑布流逻辑为 按照列数添加view标签 以下例子按照两列为例:
swan结构:
<view class="acticlelist waterfall leftwrapper" id="leftwrapper">
<view class="wrapper item" s-for="{{ leftList }}" data-id="{{item.conid}}" bindtap="active">
<view class="imgg">
<image class="wrapper-img" mode="aspectFill" src="{{ item.longimgurl }}" ></image>
</view>
<view class="title-wrapper">
<view class="title">{{ item.title }}</view>
<image class="userimg" src="{{ item.headimg }}"></image>
<text class="username">{{ item.author }}</text>
</view>
</view>
</view>
<view class="acticlelist waterfall rightwrapper" id="rightwrapper">
<view class="wrapper item" s-for="{{ rightList }}" data-id="{{item.conid}}" bindtap="active" >
<view class="imgg">
<image class="wrapper-img" mode="aspectFill" src="{{ item.longimgurl }}"></image>
</view>
<view class="title-wrapper">
<view class="title">{{ item.title }}</view>
<image class="userimg" src="{{ item.headimg }}"></image>
<text class="username">{{ item.author }}</text>
</view>
</view>
</view>
js结构:
that.getview(data, 0); //调用函数 data为后台返回数组数据
getview:function(data, i){
var that = this;
swan.createSelectorQuery().selectAll('.leftwrapper,.rightwrapper').boundingClientRect(function (rect) {
var arr1 = that.data.leftList; //左侧列表数据
var arr2 = that.data.rightList; //右侧列表数据
if( rect[0].height <= rect[1].height ){
arr1.push(data[i]); //在原有数据基础上添加新数据
that.setData({
leftList: arr1,
}, () => { //setdata callback成功会回调函数
if( i < data.length -1 ){ 当数组数据遍历完毕后执行return,否则继续调用
that.getview(data, ++i) 递归 重复调用函数
}else{
return;
}
});
}else{
arr2.push(data[i]); //在原有数据基础上添加新数据
that.setData({
rightList: arr2,
}, () => { //setdata callback
if( i < data.length -1 ){
that.getview(data, ++i)
}else{
return;
}
});
}
}).exec();
}