css左右切换时两张图片渐隐渐显重叠动效

172 阅读1分钟
 <view class="banner" :style="{height:'300px'}" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
    <image class="banner1" :class="{'disappear-banner':showAnimation}" :src="第一层张图片" mode="widthFix">
    </image>
    <image class="banner2" :class="{'appear-banner':showAnimation}" :src="第二层张图片" mode="widthFix">
    </image>
</view>
// 用户刚进入页面时prevCurrent=current,第一层图片和第二层图片一样
methods:{
    swiperChange(e) {
        if (this.currentindex === e.detail.current) return
        this.currentindex = e.detail.current
        // 页面滑动切换时,将第一层图换成第二层图片
        this.prevCurrent = this.current;
        this.showAnimation = true
        // 第二层张图片换成下一张图片
        this.current = this.infos[this.currentindex]
        // 在这1s的时间差中完成动画
        setTimeout(() => {
            this.showAnimation = false;
            // 动画完成后,第一层图片也换成第二图片,第一层图片和第二层图片一样
            this.prevCurrent = this.infos[this.currentindex]
        }, 1000)
    },
    touchStart(event) {
        // 记录触摸起始点的横坐标
        this.startX = event.touches[0].clientX;
    },
    touchMove(event) {
        // 计算滑动距离
        const currentX = event.touches[0].clientX;
        const deltaX = currentX - this.startX;
        // 判断滑动方向
        if (deltaX > 50) {
            // 向右滑
            this.status = 1
        } else if (deltaX < -50) {
            // 向左滑
            this.status = 2
        }
    },
    touchEnd() {
        if (1 === this.status) {
            this.swiperChange({
                detail: {
                    current: (0 > (this.currentindex - 1)) ? this.infos.length - 1 : this.currentindex -
                        1
                }
            })
        } else if (2 === this.status) {
            this.swiperChange({
                detail: {
                    current: ((this.infos.length - 1) < (this.currentindex + 1)) ? 0 : this
                        .currentindex + 1
                }
            })
        }
        this.status = 0
    }
}
.banner {
    position: relative;
    // 将两张图片重叠在一起
    image {
        width: 100%;
        position: absolute;
        left: 0;
        top: 0;
        z-index: 1;
    }
}

@keyframes disappear {
    0% {
        opacity: 1;
    }

    100% {
        opacity: 0;
    }
}

@keyframes appear {
    0% {
        opacity: 0;
    }

    100% {
        opacity: 1;
    }
}
// 消失和出现会有一段时间重叠
.disappear-banner {
    // 第一层图片慢慢消失
    animation: disappear 0.5s linear forwards 0.2s;
}

.appear-banner {
    // 第二层图片慢慢出现 
    animation: appear 0.5s linear forwards;
}

效果图如下: pan.baidu.com/s/1P-GnqZ3p…

参考链接:juejin.cn/post/730190…