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

点击按钮时重置并重新触发CSS动画的实现问题

问题原因

原有逻辑仅修改了动画的播放状态,而CSS动画默认仅执行1次,首次播放结束后会停在最终帧,后续仅修改播放状态无法触发动画重新播放。同时原有代码还存在2处语法问题:addeventlistener拼写错误、点击回调中未调用音频播放函数playSound。

修复方案

推荐使用类名切换的方式实现动画重置,兼容性更好、逻辑更清晰:

1. 修改CSS代码

@keyframes color {
  from {background-color: red;}
  to {background-color: blue;}
}
#button {
  /* 初始不绑定动画,通过类动态控制 */
}
.button-animate {
  animation: color 2s linear forwards;
}

2. 修改JS代码

const sounds = [
  "https://s3.amazonaws.com/freecodecamp/simonSound1.mp3",
  "https://s3.amazonaws.com/freecodecamp/simonSound2.mp3",
  "https://s3.amazonaws.com/freecodecamp/simonSound3.mp3",
  "https://s3.amazonaws.com/freecodecamp/simonSound4.mp3"
];
const button = document.getElementById('button');
const audio = new Audio();

function playSound(){
  const rand = Math.floor(Math.random() * sounds.length);
  audio.src = sounds[rand];
  audio.play();
}

function restartAnimation() {
  // 先移除动画类
  button.classList.remove('button-animate');
  // 触发浏览器重排,让浏览器确认动画已移除,否则会判定类未变更不重新触发动画
  void button.offsetWidth;
  // 重新添加动画类,触发从头播放
  button.classList.add('button-animate');
}

// 修正事件监听拼写,同时绑定音频播放+动画触发逻辑
button.addEventListener('click', () => {
  playSound();
  restartAnimation();
});

无需修改CSS的替代方案

如果不想改动原有CSS,也可以直接通过修改行内动画属性实现重置:

// 直接替换原有function1逻辑即可
function function1(){
  playSound();
  button.style.animationName = 'none';
  void button.offsetWidth;
  button.style.animationName = 'color';
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:09:03