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

JavaScript与CSS动画时序不一致问题求助

问题解决:文本切换动画时序异常

问题描述

通过定时器切换数组中5行文本时,CSS动画时序存在问题:文本透明度降至0后,下一段文本出现的间隔过长。预期流程应为:文本显示→向下滑动动画→淡出→下一段文本出现。

问题原因

  1. 当前@keyframes slidesdown的关键帧设置存在重叠(50%节点同时作为两个阶段的分界),导致动画的淡出阶段和文本切换不同步。
  2. JS的setInterval固定5秒切换文本,未与CSS动画时序对齐,动画仍处于后期淡出状态时就切换文本,造成视觉上的间隔过长。

解决方案

1. 调整CSS动画关键帧

重新划分动画阶段,明确显示、下滑淡出、隐藏的时间区间,确保淡出完成后预留短暂空白期用于文本切换:

@keyframes slidesdown {
  0%, 30% { /* 前30%时间保持显示状态 */
    transform: translate(0, 0em);
    opacity: 1;
  }
  30% to 70% { /* 中间40%时间完成下滑+淡出 */
    transform: translate(0, 1em);
    opacity: 0;
  }
  70%, 100% { /* 最后30%时间保持隐藏,等待文本切换 */
    transform: translate(0, 1em);
    opacity: 0;
  }
}

p {
  height: 2em;
  position: absolute;
  font-size: 32px;
  color: var(--darkest--colour);
  margin-left: 1em;
  width: 12em;
  margin-top: 0em;
  animation: slidesdown 5s ease infinite;
}

2. 同步JS定时器与动画时序

修改JS逻辑,在动画进入隐藏阶段后切换文本,并重置动画状态确保新文本能正确触发动画:

let textElement = document.querySelector("p")
let textArray = [
  "Are you looking for a quick learner?",
  "Someone who is ever evolving?",
  "Someone who strives to improve their knowledge?",
  "Someone who loves problem-solving and finding solutions?",
  "Someone who has the tenacity to succeed?"
]
let index = 0;
textElement.innerText = textArray[index]

setInterval(() => {
  // 重置动画状态,触发重绘
  textElement.style.animation = 'none';
  void textElement.offsetWidth;
  
  index = (index + 1) % textArray.length
  textElement.innerText = textArray[index]
  
  // 重新绑定动画
  textElement.style.animation = 'slidesdown 5s ease infinite';
}, 5000)

3. 精准同步动画与切换(可选)

若要避免定时器误差,可监听animationend事件,在每次动画结束后切换文本:

let textElement = document.querySelector("p")
let textArray = [
  "Are you looking for a quick learner?",
  "Someone who is ever evolving?",
  "Someone who strives to improve their knowledge?",
  "Someone who loves problem-solving and finding solutions?",
  "Someone who has the tenacity to succeed?"
]
let index = 0;
textElement.innerText = textArray[index]

function switchText() {
  textElement.style.animation = 'none';
  void textElement.offsetWidth;
  
  index = (index + 1) % textArray.length
  textElement.innerText = textArray[index]
  
  textElement.style.animation = 'slidesdown 5s ease infinite';
}

textElement.addEventListener('animationend', switchText);
textElement.style.animation = 'slidesdown 5s ease infinite';

修改后效果

文本会按照显示30%时长→下滑淡出40%时长→隐藏30%时长→切换新文本并重复的节奏执行,完美匹配预期流程,无过长间隔问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:50:35