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

如何修改CSS文字动画,拆分显隐效果实现单次触发控制

以下是符合要求的实现方案,将显示、消失逻辑拆分为两个独立的自定义类,每个类绑定的动画仅执行一次,可直接通过JS动态调用:

1. 调整后完整CSS代码

/* 基础样式保留,仅修改动画相关部分 */
body {
  background: white;
  color: #555;
  font-family: "Roboto";
  font-weight: 300;
  font-size: 32px;
  padding-top: 40vh;
  height: 100vh;
  overflow: hidden;
}

.theSidenav {
  width: 20vw !important;
}

.animation_container {
  width: 14vw;
  display: grid;
  grid-template-columns: 16vw 10vw;
  grid-gap: 10px;
}

.first_animation {
  padding-right: 0;
  margin-right: 0;
  opacity: 0; /* 默认隐藏,等待动画触发 */
}

.first_animation,
.second_animation {
  overflow: hidden;
}

.second_animation {
  width: 0px;
  opacity: 0; /* 默认隐藏 */
}

.second_animation span {
  margin-left: -800px;
}

/* 显示动画自定义类:触发后执行一次显示流程 */
.anim-show .first_animation {
  animation: showup 3s forwards 1;
}
.anim-show .second_animation {
  animation: reveal 3s forwards 1;
}
.anim-show .second_animation span {
  animation: slidein 3s forwards 1;
}

/* 消失动画自定义类:触发后执行一次消失流程 */
.anim-hide .first_animation {
  animation: hideup 2s forwards 1;
}
.anim-hide .second_animation {
  animation: unreveal 2s forwards 1;
}
.anim-hide .second_animation span {
  animation: slideout 2s forwards 1;
}

/* 显示阶段关键帧,可自行调整时间比例适配节奏 */
@keyframes showup {
  0% { opacity: 0; }
  20% { opacity: 1; }
  100% { opacity: 1; }
}
@keyframes slidein {
  0% { margin-left: -800px; }
  60% { margin-left: -800px; }
  100% { margin-left: 0px; }
}
@keyframes reveal {
  0% { opacity: 0; width: 0px; }
  60% { opacity: 1; width: 0px; }
  100% { opacity: 1; width: 355px; }
}

/* 消失阶段关键帧 */
@keyframes hideup {
  0% { opacity: 1; }
  100% { opacity: 0; }
}
@keyframes slideout {
  0% { margin-left: 0px; }
  100% { margin-left: -800px; }
}
@keyframes unreveal {
  0% { opacity: 1; width: 355px; }
  100% { opacity: 0; width: 0px; }
}

p {
  font-size: 12px;
  color: #999;
  margin-top: 200px;
}

2. JS调用控制方法

不需要修改原有HTML结构,直接通过操作类名触发对应动画即可:

// 触发所有菜单项的显示动画
document.querySelectorAll('.animation_container').forEach(el => {
  el.classList.remove('anim-hide')
  el.classList.add('anim-show')
})

// 需要触发消失时执行
document.querySelectorAll('.animation_container').forEach(el => {
  el.classList.remove('anim-show')
  el.classList.add('anim-hide')
})

内容的提问来源于stack exchange,提问作者Josef Lundström

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:06:02