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

CSS如何实现hover触发动画后,取消hover时仍完整播放全段动画

实现方案

问题原因

你当前的动画直接绑定在:hover伪类上,鼠标移出元素后伪类失效,动画属性会被直接移除,因此动画会中途中断。

方案1:纯CSS实现(无需额外JS代码)

直接修改CSS即可,沿用原有HTML代码:

.textBox {
  height: 500px;
  width: 500px;
  font-size: 1.5rem;
  font-weight: 800;
  display: flex;
  justify-content: center;
  align-items: center;
  letter-spacing: 10px;
}

.textBox__Item {
  /* 默认声明动画,设置为暂停状态,播放完毕后保持最终帧 */
  animation: rubberFonts 1.5s forwards paused;
}

.textBox__Item:hover {
  /* hover时重置动画名称触发重放,同时切换为运行状态 */
  animation-name: rubberFonts;
  animation-play-state: running;
}

方案2:JS实现(可控性更高,无重复触发问题)

适合需要更灵活控制动画的场景,修改后的CSS和新增JS代码如下,HTML无需改动:

修改后的CSS代码

.textBox {
  height: 500px;
  width: 500px;
  font-size: 1.5rem;
  font-weight: 800;
  display: flex;
  justify-content: center;
  align-items: center;
  letter-spacing: 10px;
}

/* 动画绑定到独立的触发类 */
.playRubber {
  animation: rubberFonts 1.5s;
}

新增JS代码

const textItems = document.querySelectorAll('.textBox__Item')
textItems.forEach(item => {
  // 鼠标进入时添加动画类触发动画
  item.addEventListener('mouseenter', () => {
    item.classList.add('playRubber')
  })
  // 动画播放完毕后移除类,方便下次hover触发
  item.addEventListener('animationend', () => {
    item.classList.remove('playRubber')
  })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:18:00