微信小程序实现瀑布流

实现的步骤:
逐步处理列表的数据,把数据放到高度比较小数组中。

这个时候我们需要获取到图片的高度,并且计算左右两边数组高度,把新的数据放到高度比较小的数组中。

加载到后端的数据

设置我们需要的属性,这里我们需要leftList、rightList、leftHeight、rightHeight

遍历数组,通过wx.getImageInfo获取到每个元素图片的宽度高度(需要配置download的域名)

判断这个元素应该被放在左边还是右边(放在数组高度低的一边)

处理完数据之后,把数据设置到data上

在前端展示这些数据(图片需要加上mode="widthFix",宽度固定,高度自适应,保持宽高比)

/* 递归 */
getpost() {
    if (this.data.postList.length == 0) {
      this.setData({
        show: false
      })
      return
    }
    let item = this.data.postList.shift()
    wx.getImageInfo({
      src: item.avatar,
      success: (res) => {
        if (this.data.leftHeight > this.data.rightHeight) {
          this.data.rightList.push(item)
          this.data.rightHeight += res.height / res.width
        } else {
          this.data.leftList.push(item)
          this.data.leftHeight += res.height / res.width
        }
      },
      complete: () => {
        this.setData({
          rightList:this.data.rightList,
          leftList:this.data.leftList
        })
        this.getpost()
      }
    })
 
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    getpostList().then(res => {
      console.log(res);
      this.data.postList = res.data.rows
      this.getpost()
    })
  },


 

猜你喜欢

转载自blog.csdn.net/weixin_47619284/article/details/126843727