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

如何用原生JS和CSS实现点击按钮后在元素fadeoutLeft动画75%进度显示另一元素

可以实现,有两种常用方案:

方案1:纯CSS对齐动画时序(推荐,实现成本最低)

你当前fadeOutLeft动画总时长固定为10000ms,75%进度对应7500ms的时间点,直接给box2配置延迟显示的动画即可,无需额外监听逻辑:
修改CSS部分:

/* 新增box2淡入动画 */
@keyframes fadeIn {
  to {
    opacity: 1;
  }
}
.box2 {
  background-color: #eac;
  opacity: 0;
}
/* 新增触发box2显示的类 */
.box2.show {
  animation: fadeIn 0.3s forwards;
  animation-delay: 7500ms; /* 对应box1动画75%的时间点 */
}

修改JS点击逻辑:

document.getElementById("abc").addEventListener("click", function () {
  document.querySelector(".box1").classList.add("fadeOutLeft");
  document.querySelector(".box2").classList.add("show");
});

如果后续调整box1的动画时长,需要同步修改box2的animation-delay值为总时长的75%即可。

方案2:JS监听动画进度(适合动画时长不固定、需要动态判断进度的场景)

如果动画时长是动态变化的,可以通过requestAnimationFrame实时读取动画执行进度,到75%时触发回调:
替换你的JS部分为以下代码即可:

document.getElementById("abc").addEventListener("click", function () {
  const box1 = document.querySelector(".box1");
  const box2 = document.querySelector(".box2");
  box1.classList.add("fadeOutLeft");
  // 自动读取box1的动画总时长,适配动态时长
  const totalDuration = parseFloat(getComputedStyle(box1).animationDuration) * 1000;
  const triggerTime = totalDuration * 0.75;
  let startTimestamp = null;
  let hasTriggered = false;
  function checkProgress(timestamp) {
    if (!startTimestamp) startTimestamp = timestamp;
    const elapsedTime = timestamp - startTimestamp;
    // 达到75%进度且未触发过时执行
    if (elapsedTime >= triggerTime && !hasTriggered) {
      hasTriggered = true;
      box2.style.opacity = 1;
      return;
    }
    // 动画未结束则继续监听
    if (elapsedTime < totalDuration) {
      requestAnimationFrame(checkProgress);
    }
  }
  requestAnimationFrame(checkProgress);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:45:05