【问题标题】:reset and restart animation on button click [duplicate]单击按钮时重置并重新启动动画[重复]
【发布时间】:2021-10-30 08:31:06
【问题描述】:

我有一个按钮元素,每次单击它时都会从数组中播放随机音频文件。我还想让它在单击时播放动画,并在每次单击后重置和重播。下面的代码是我到目前为止所拥有的,这可以工作,但是动画只播放一次,然后按钮元素是静态的。任何想法将不胜感激!

#button {
animation: color 2s linear;
animation-play-state: paused;
}
@keyframes color {
from {background-color: red;}
to {background-color: blue;}
}
<button id="button">Click To Play</button>
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 audio = new Audio();

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

button.addeventlistener('click',function1);

function function1(){
button.style.webkitAnimationPlayState = 'running'; 
}

【问题讨论】:

    标签: javascript animation event-handling css-animations event-listener


    【解决方案1】:

    基本上发生的事情是你正在播放动画,它已经到了最后,但它没有被重置。

    你可以在你的css中使用animation-name,然后在js中,清除动画名称,然后重新设置它来再次播放你的动画。

    另一种方法是将动画名称放在单独的类中,然后根据需要在元素上添加/删除该类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 2014-01-24
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多