小程序瀑布流無限加載


由於想做成瀑布流,故一開始使用如下的方式:

.waterfall-container {
    column-count: 2;
    column-gap: 30rpx;
}

但是,由於這種  column-count:2   ,是由上往下排的,所以再加載新的一頁的時候,原來在頁首的會被頂到底部,導致整個邏輯是錯誤的。

 

故,需要修改一下頁面的實現思路

1. 在頁首加入預加載的圖片的不顯示的塊,加載圖片時,會觸發事件,

2. 在事件處理 function 中,進行圖片的分發,根據當前的兩列的實際高度,分發到兩列中。

 

具體實現:

在頁首加上 display: none 的塊,用於預加載圖片。

<view style="display:none">
    <image wx:for="{{prefetch_products.rows}}" data-id="{{item.id}}" data-image-src="{{item.cover}}" wx:for-item="item" src="{{item.cover}}"
        bindload="onImageLoad"></image>
</view>

 

JS:

onImageLoad: function (e) {
        var oriHeight = e.detail.height,
            oriWidth = e.detail.width,
            scale = oriHeight / oriWidth,
            destWidth = this.data.imageWidthRpx * rpxScale,     // 在不同機型中的具體圖片寬度
            destHeight = scale * destWidth,
            id = e.currentTarget.dataset.id,
            src = e.currentTarget.dataset.imageSrc;

        // 分發到兩邊
        var col1 = this.data.col1,
            col2 = this.data.col2,
            loadingCount = this.data.loadingCount;

        // 比較兩邊的height
        // 哪個矮分發到哪個
        if (col1.height <= col2.height) {
            col1.images.push({
                id: id,
                src: src
            });
            col1.height += (destHeight + 39 * rpxScale); // 補償 padding 的高度
            --loadingCount;
        } else {
            col2.images.push({
                id: id,
                src: src
            });
            col2.height += (destHeight + 39 * rpxScale); // 補償 padding 的高度
            --loadingCount;
        }

        if (!loadingCount) {
            this.setData({
                prefetch_products: []
            });
        }

        this.setData({
            loadingCount: loadingCount,
            col1: col1,
            col2: col2
        });
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM