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

动画结束后如何重新启用btRace按钮?

问题描述

我有btRace和btStop两个按钮:

  • 点击btRace会触发所有bt1按钮,让所有车辆动画同时播放
  • 点击btStop会触发所有bt2按钮,停止动画

当前问题:点击btRace后,动画自然结束但btRace仍处于不可点击状态,必须先点击btStop才能再次触发 race,可动画已经停止,这个交互逻辑有误导性,希望动画结束后btRace自动恢复可点击状态。

解决方案

核心思路是监听动画的animationend事件,在动画自然结束时同步恢复btRace的可点击状态,同时处理手动停止的场景。

步骤1:给btRace添加禁用/启用逻辑

首先确保点击btRace后立即禁用,避免重复触发:

// 修改btRace的点击事件
this.btRace.addEventListener('click', () => {
  this.btRace.disabled = true; // 点击后禁用按钮
  playBts.forEach(bt => bt.click()); // 触发所有bt1按钮
});

步骤2:监听动画结束事件,恢复按钮状态

在animation函数中,给车辆图片绑定animationend事件,当动画自然结束时,执行停止逻辑并检查所有动画是否完成,完成后启用btRace:

function animation(img) {
  let status = 'started';
  let aPICallCarEngineState = new APICallCarEngineState(editingCarId, status);
  aPICallCarEngineState.processRequestJSON((res) => {
    res.velocity = res.velocity * 0.01;
    res.distance = 500;

    // 先移除旧的监听,避免重复绑定
    img.removeEventListener('animationend', onAnimationEnd);
    // 绑定动画结束事件,绑定this指向
    img.addEventListener('animationend', onAnimationEnd.bind(this));

    img.style.animation = `car_move ${res.velocity}s ease-in`;
  });

  // 动画结束回调
  function onAnimationEnd() {
    stopAnimation(); // 执行停止动画的逻辑
    // 检查所有车辆的动画是否都已结束
    const allCarsStopped = Array.from(document.querySelectorAll('[style*="car_move"]')).length === 0;
    if (allCarsStopped) {
      this.btRace.disabled = false; // 所有动画结束后启用按钮
    }
  }
}

步骤3:优化btStop的点击逻辑

点击btStop时,除了停止动画,也要立即启用btRace:

this.btStop.addEventListener('click', () => {
  bt2.click();
  this.btRace.disabled = false; // 手动停止后立即恢复按钮可点击
});

可选:用计数器精准跟踪动画状态(多车辆场景)

如果有多个车辆,用计数器跟踪正在运行的动画数量会更准确:

  1. 在构造函数中初始化计数器:
constructor() {
  // ... 其他初始化代码
  this.activeAnimations = 0;
}
  1. 在animation函数中更新计数器:
function animation(img) {
  this.activeAnimations++; // 动画开始时计数+1
  let status = 'started';
  let aPICallCarEngineState = new APICallCarEngineState(editingCarId, status);
  aPICallCarEngineState.processRequestJSON((res) => {
    res.velocity = res.velocity * 0.01;
    res.distance = 500;

    img.removeEventListener('animationend', onAnimationEnd);
    img.addEventListener('animationend', onAnimationEnd.bind(this));

    img.style.animation = `car_move ${res.velocity}s ease-in`;
  });

  function onAnimationEnd() {
    stopAnimation();
    this.activeAnimations--; // 动画结束时计数-1
    if (this.activeAnimations === 0) {
      this.btRace.disabled = false;
    }
  }
}
  1. 点击btStop时重置计数器:
this.btStop.addEventListener('click', () => {
  bt2.click();
  this.activeAnimations = 0;
  this.btRace.disabled = false;
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:41:06