微信小程序瀑布流布局无限加载

1. 在html中动态加载图片(表示笔者并没有尝试过,记在这里可以试试)

通常使用new Image()创建一个图片对象,然后通过动态加载url指向图片,并获取图片信息。

2. 在小程序中可以使用来实现 ,image有一个属性叫bindload(当图片载入完毕时,发布到 AppService 的事件名,事件对象event.detail = {height:'图片高度px', width:'图片宽度px'}。简单来说就是用它来获取图片的高和宽。

3.简述一下思路:要做一个固定为2列的布局,图片数据将根据图片的高度,决定动态的添加到左列还是右列。

来实现一下:首先来做一个两列的布局


  
    
      
        
      
    
    
      
        
      
    
  

然后要在页面上放一个隐藏的区域,用它来获取图片的高度


  

是不是要监听滚动到底部?哈哈,非常完美scroll-view有一个属性叫做bindscrolltolower,当滚动到最右端或最低端就会触发这个事件。ok贴代码(loadImages方法到最底部重新加载一组图片)

loadImages: function () {
        let images = [
            { pic: "../../images/1.png", height: 0 },
            { pic: "../../images/2.png", height: 0 },
            { pic: "../../images/3.png", height: 0 },
            { pic: "../../images/4.png", height: 0 },
            { pic: "../../images/5.png", height: 0 },
            { pic: "../../images/6.png", height: 0 },
            { pic: "../../images/7.png", height: 0 },
            { pic: "../../images/8.png", height: 0 },
            { pic: "../../images/9.png", height: 0 },
            { pic: "../../images/10.png", height: 0 },
            { pic: "../../images/11.png", height: 0 },
            { pic: "../../images/12.png", height: 0 },
            { pic: "../../images/13.png", height: 0 },
            { pic: "../../images/14.png", height: 0 }
        ];

        let baseId = "img-" + (+new Date());

        for (let i = 0; i < images.length; i++) {
            images[i].id = baseId + "-" + i;
        }

        this.setData({
            loadingCount: images.length,
            images: images
        });
        console.log(this.data.images)
    }

加载到的图片分别放在左右列里面

 onImageLoad: function (e) {
        let imageId = e.currentTarget.id;
        let oImgW = e.detail.width;         //图片原始宽度
        let oImgH = e.detail.height;        //图片原始高度
        let imgWidth = this.data.imgWidth;  //图片设置的宽度
        let scale = imgWidth / oImgW;        //比例计算
        let imgHeight = oImgH * scale;      //自适应高度

        let images = this.data.images;
        let imageObj = null;

        for (let i = 0; i < images.length; i++) {
            let img = images[i];
            if (img.id === imageId) {
                imageObj = img;
                break;
            }
        }

        imageObj.height = imgHeight;

        let loadingCount = this.data.loadingCount - 1;
        let col1 = this.data.col1;
        let col2 = this.data.col2;

        if (col1H <= col2H) {
            col1H += imgHeight;
            col1.push(imageObj);
        } else {
            col2H += imgHeight;
            col2.push(imageObj);
        }

        let data = {
            loadingCount: loadingCount,
            col1: col1,
            col2: col2
        };

        if (!loadingCount) {
            data.images = [];
        }

        this.setData(data);
    },
大概的流程就是这样子,还没有明白的宝宝请戳原版https://www.jianshu.com/p/260f2623562d






你可能感兴趣的:(微信小程序瀑布流布局无限加载)