You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中如何阻止文本渐变动画完成后自动重置?

问题:文本动画完成后无法保持消失状态

我想复刻一个旅行机构着陆页的文本滑动消失动画,但遇到问题:动画完成后文本会回到初始状态,无法保持滑动消失后的状态。我原本以为设置animation-fill-mode: forwards能阻止动画重置,但没用。

以下是我目前的CSS代码:

.title{
    pointer-events: none;
    grid-area: 1/2/2/3;
    place-self: center;
    position: relative;
    background: linear-gradient(90deg,
      rgba(255,255,255,0) 0%,
      rgba(255,255,255,1) 5%,
      rgba(255,255,255,1) 100%);
    background-size: 130%;
    background-position-x: 50%;
    background-repeat: no-repeat;
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
}

@keyframes titleAnimationSequence{
    0% {
      background-position-x: 50%;
    }
    100% {
      background-position-x: -700%;
      opacity: 0;
    }
  }

.titleAnimation-enter-active{
    animation: titleAnimationSequence .3s ease-out;
    animation-fill-mode: forwards;
    -webkit-animation-fill-mode: forwards;
}

我的Vue模板代码如下:

<template>
    <!--stuff-->
    <h1 v-if="!plusButtonComplete" class="title align-middle sm:text-[length:var(--text-ultraJumbotron-2)] md:text-[length:var(--text-ultraJumbotron-3)] z-30">
        Explore
      </h1>
      <Transition name="titleAnimation">
        <h1 v-if="plusButtonComplete" class="title align-middle sm:text-[length:var(--text-ultraJumbotron-2)] md:text-[length:var(--text-ultraJumbotron-3)]">
            Explore
        </h1>
      </Transition>
    <!-- more stuff -->
</template>

请问如何让它保持最终状态,直到我手动切换回来?


解决方案

问题出在Vue的Transition组件机制:动画结束后,titleAnimation-enter-active类会被自动移除,而animation-fill-mode: forwards仅在该类存在时生效,所以动画状态会被重置。

解决方法是在动画结束后,用一个持久化的类来固定最终状态:

  1. 新增一个CSS类,定义动画的最终状态:
.title--hidden {
  background-position-x: -700%;
  opacity: 0;
}
  1. 修改Transition组件,通过@after-enter钩子在动画完成后给元素添加这个类:
<Transition name="titleAnimation" @after-enter="(el) => el.classList.add('title--hidden')">
  <h1 v-if="plusButtonComplete" class="title align-middle sm:text-[length:var(--text-ultraJumbotron-2)] md:text-[length:var(--text-ultraJumbotron-3)]">
      Explore
  </h1>
</Transition>

这样动画结束后,元素会一直保留title--hidden类的状态,直到你通过修改plusButtonComplete的值手动切换回来。

另外注意:你提供的CSS代码中.titleAnimation-enter-active的大括号没有闭合,记得补上,否则会影响CSS解析。


内容的提问来源于stack exchange,提问作者Optiq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 21:47:35