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

如何让CSS transform translateX动画停止后保持位置并设为默认状态?

解决地面动画停止后跳回初始位置并设置默认位置的问题

原方案依赖CSS类切换动画,移除类时元素会重置到初始状态,导致地面跳回起点。以下是更可靠的实现方案,用JS直接控制动画状态与位置,支持暂停时保持当前位置、设置默认位置:

修改后的CSS

.surface {
  height: 350px;
  width: 300vw;
  background: url("floor.png");
  display: block;
  position: absolute;
  bottom: 0%;
  background-repeat: repeat-x;
  transform: translateX(0); /* 初始位置 */
}

修改后的JS

$(document).ready(function() {
  const $surface = $('.surface');
  const frog = document.getElementById('frog'); // 确保青蛙元素设置id="frog"
  let currentX = 0;
  let isAnimating = false;
  let animationId;
  // 匹配原动画速度:10秒移动1080px,每帧(约16ms)移动1.728px
  const frameSpeed = (1080 / 10000) * 16;

  // 动画核心逻辑
  function animateSurface() {
    currentX -= frameSpeed;
    // 循环重置偏移量,保持背景重复的视觉连续性
    if (currentX <= -1080) {
      currentX = 0;
    }
    $surface.css('transform', `translateX(${currentX}px)`);
    animationId = requestAnimationFrame(animateSurface);
  }

  // 页面加载时读取保存的默认位置
  const savedX = localStorage.getItem('defaultSurfaceX');
  if (savedX !== null) {
    currentX = parseInt(savedX);
    $surface.css('transform', `translateX(${currentX}px)`);
  }

  // Enter键控制动画启停
  $(document).on('keypress', function(e) {
    if (e.which === 13) {
      isAnimating = !isAnimating;

      // 切换青蛙动图
      if (frog.src.includes('FrogIdle.gif')) {
        frog.src = 'forgjump.gif';
      } else {
        frog.src = 'FrogIdle.gif';
      }

      if (isAnimating) {
        animationId = requestAnimationFrame(animateSurface);
      } else {
        cancelAnimationFrame(animationId);
        // 将当前位置存入本地存储,作为下次加载的默认位置
        localStorage.setItem('defaultSurfaceX', currentX);
      }
    }
  });
});

关键说明

  1. 用requestAnimationFrame替代CSS动画,直接操控transform属性,暂停时不会重置位置。
  2. currentX实时记录地面偏移量,停止动画时将其存入localStorage,页面刷新后自动读取并应用,实现默认位置功能。
  3. 保留原动画的循环逻辑:偏移量达到-1080px时重置为0,保证背景重复的视觉效果与原动画一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:41:59