在Vue中,实现点击时暂停动画效果可以通过以下步骤来完成:
- 在template中设置元素,为其添加一个ref属性,以便在Vue实例中使用这个元素。
“`html
“`
- 在Vue生命周期的
mounted
钩子里,为该元素添加动画效果,并在动画对象中添加一个停止播放/记录进度的变量。
“`javascript
export default {
data() {
return {
isAnimationPlaying: false,
animation: null
};
},
mounted() {
this.initializeAnimation();
},
methods: {
initializeAnimation() {
this.animation = this.$refs.animationContainer.querySelector(“.animation”).animate(
{
opacity: 0,
transform: “scale(1, 0)”
},
{
duration: 300,
easing: “ease-in-out”,
iterations: Infinity
}
);
},
toggleAnimation() {
if (this.isAnimationPlaying) {
this.animation.pause();
this.isAnimationPlaying = false;
} else {
this.animation.play();
this.isAnimationPlaying = true;
}
}
}
};
“`
- 在CSS中设置动画样式,使元素在一定时间后自动消失。
“`css
.animation-container {
width: 200px;
height: 200px;
background-color: lightblue;
display: flex;
justify-content: center;
align-items: center;
position: relative;
}
@keyframes fadeInOut {
0% {
opacity: 0;
transform: scale(1, 0);
}
100% {
opacity: 1;
transform: scale(1, 1);
}
}
动画-container .animation {
width: 100%;
height: 100%;
background-color: #42b983;
color: white;
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
animation: fadeInOut 300ms ease-in-out infinite;
}
“`
通过以上步骤,我们可以在点击按钮时切换动画的播放状态。当点击按钮时,动画会暂停或恢复。