小程序:无限自动滚动的Gallery

3,789 阅读2分钟

遇到一个需求,需要在小程序内实现自动轮播的画廊效果,如果是网页版的话有大量现成的库可以用,但小程序找了一圈没找到有类似的库,只好自己想办法了。

在踩了多个坑之后找到最简单的方法,就是用CSS animation来实现,但缺点就是不能手动拖动。

先贴一下效果图

gallery

第一步 html

因为要无限滚动,所以放完在最后一个图之后需要切换回第一个图。为了让用户感知不到这个切换过程,需要将最开始图片复制后末尾,小程序里把wx:for复制一遍就行了,注意要修改wx:key的值,避免重复。

为啥是复制全部图片呢,主要是因为keyframes的值不能动态设置,复制全部后只需要将end进度值设置为-50%即可。

<view class="series">
    <view
        style="animation: {{duration}}ms scroll-animation linear infinite;width: {{seriesWidth*2}}rpx"
        class="images">
        <view class="row" wx:for="{{productSeries}}" wx:key="{{index}}">
            <image
                wx:for="{{item}}"
                wx:for-item="img"
                wx:for-index="imgIndex"
                wx:key="{{img + imgIndex}}"
                src="{{img}}"
            ></image>
            <image
                wx:for="{{item}}"
                wx:for-item="img"
                wx:for-index="imgIndex"
                wx:key="{{img + imgIndex}}-extra"
                src="{{img}}"
            ></image>
        </view>
    </view>
</view>

第二步 css

CSS动画很简单,让gallery转动到-50%的时候跳回0%,并设置infinite。使用style而非class的原因是画廊总长不确定,动画的时长根据图片数量来设置。width也是需要动态设置,自动计算的width会有问题。

.series {
    overflow: hidden;
    .images {
        min-width: 100%;
        .row {
            white-space: nowrap;
            line-height: 1;
            &:last-child {
                transform: translateX(-100rpx);
            }
        }
        image {
            width: 180rpx;
            height: 180rpx;
            margin: 0 10rpx 8rpx 0;
        }
    }
}
@keyframes scroll-animation {
        from {
            transform: translateX(0);
        }
        to {
            transform: translateX(-50%);
        }
    }

第三步 js

我们还需要通过js计算动画时长和view的长度,数字190是image width + margin-right的值。最后要再减一次margin-right的原因我也不确定,但不减这个值的话动画最后会有一点卡顿的感觉,显得不太流畅,希望有大佬解答一下原理。

data = {
    productSeries: [
        [
            '/images/house1.png',
            '/images/house2.png',
            '/images/house3.png',
            '/images/house2.png',
            '/images/house3.png',
            '/images/house4.png'
        ],
        [
            '/images/house1.png',
            '/images/house2.png',
            '/images/house3.png',
            '/images/house2.png',
            '/images/house3.png',
            '/images/house4.png'
        ]
    ],
    speed: 40,
    seriesWidth: 400,
    duration: 60000
}
onShow() {
    if (this.productSeries[0].length > 4) {
        this.seriesWidth = 190 * this.productSeries[0].length - 10
        this.duration = Math.floor(this.seriesWidth / this.speed * 1000)
    } else { // 当一行图片太少时就没必要加动画了
        this.seriesWidth = null
        this.duration = 0
    }
}