我正在开发一个 Vue.js 组件,其中创建一个翻转动画,其中的图像每隔几秒会变化一次。目标是随机更改图像,但在转换过程中存在问题。
我想要的是:
- 可能的图片从文件夹中加载。我们从一张图像开始,然后随机确定下一张图像。
- 图像之间有翻转动画。
会发生什么:
这个逻辑有一个缺陷。图像 1 和图像 2 之间的动画按预期工作。但在从图像 2 到图像 3 的动画中,图像 1 会短暂地重新出现。(这种情况也发生在所有后续动画中。)
您可以在此处找到此问题的屏幕录像。
代码:
模板:
<template>
<div class="start-screen">
<div class="container">
<div id="card">
<div
v-for="(image, index) in images"
:key="index"
:class="['flip-page', { active: index === currentIndex, turnedLeft: index === previousIndex }]"
:style="{ backgroundImage: `url(${image})` }"
></div>
</div>
</div>
</div>
</template>
脚本:
<script>
export default {
name: "StartScreen",
data() {
return {
images: [],
currentIndex: 0,
previousIndex: null, // Track the last image for smooth transition
};
},
methods: {
loadImages() {
const context = require.context("../assets/icons", false, /\.(png|jpe?g|svg)$/);
this.images = context.keys().map(context);
},
getRandomIndex() {
if (this.images.length <= 1) return 0;
let newIndex;
do {
newIndex = Math.floor(Math.random() * this.images.length);
} while (newIndex === this.currentIndex); // Avoid immediate repetition
return newIndex;
},
nextSlide() {
this.previousIndex = this.currentIndex; // Store the previous image index
this.currentIndex = this.getRandomIndex(); // Get a new random image
},
},
mounted() {
this.loadImages();
setInterval(this.nextSlide, 6000); // Flip every 6 seconds
},
};
</script>
风格:
<style scoped>
.start-screen {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
/* Container for the flip effect */
.container {
width: 260px;
height: 260px;
position: relative;
perspective: 800px;
}
/* Stacked images */
#card {
width: 100%;
height: 100%;
position: absolute;
}
/* Flip animation for each page */
.flip-page {
width: 100%;
height: 100%;
position: absolute;
background-size: cover;
background-position: center;
border-radius: 10px;
backface-visibility: hidden;
transition: transform 3s;
transform: rotateY(180deg);
}
/* Flip the active page forward */
.active {
transform: rotateY(0deg);
z-index: 2;
}
/* Only show the most recent previous page */
.turnedLeft {
transform: rotateY(-180deg);
z-index: 1;
}
</style>
问: 谁能解释为什么会发生这种情况,我该如何解决它,以确保只有当前和下一张图片可见,并且第三张图片不会闪烁?非常感谢!
只需隐藏
.flip-page
既不是.active
也不是的元素.turnedLeft
,如下所示::not
CSS 伪类- MDN 文档或者简单地说,相同: