是否可以在单击时将类(特别是其动画)重置回其初始状态

7 javascript css animation css3 css-animations

我有一个动画脚本,应该div根据鼠标事件(如mousemove,click等)改变动画.一个问题是,每次单击时都应该启动动画div.

在Chrome中,唯一可用于测试*的浏览器(请参阅底部的注释),这不起作用:

//The non-clicked class is "notClicked"
//The clicked class is "clicked"
//The will be referred to as elem
elem.onclick = function(){
  elem.className="notClicked";
  elem.className="clicked";
} 
Run Code Online (Sandbox Code Playgroud)

单击该项一次时,它按预期工作,但如果单击两次(触发两个事件),会发生什么:

  • 在元素检查器中,该类显示更改
  • 然而,动画继续,好像该类永远不会改变,并且第二个事件从未被触发.

注意:我很遗憾只有一个chromebook,我不能在其他浏览器上进行测试,因为我只有chrome.我知道我很便宜.对不起.

附加说明:本机javascript是首选,但jQuery解决方案也不错.

更多注意事项:为了清楚起见,因为我认为我让很多人感到困惑,当第二次点击对象时,动画应该重新开始,而不是继续.

JS FIDDLE(根据要求): 那个小提琴

Har*_*rry 6

你需要在删除类和重新添加之间使用一个超时,否则这个类缺少的时间对于浏览器注意到差异来说太微不足道了.

以下是我的意思的一个例子.您将能够看到每次单击该元素时,它都会返回到其原始状态,并且动画将重新开始.

window.onload = function() {
  var el = document.querySelector('div');
  el.addEventListener('click', function() {
    if (this.className == '') { /* for the first click, add class immediately */
      this.className = 'animated';
    } else { /* for second and subequent clicks, first remove class and add after timeout */
      this.className = '';
      window.setTimeout(function() {
        el.className = 'animated';
      }, 100);
    }
  });
}
Run Code Online (Sandbox Code Playgroud)
div {
  height: 200px;
  width: 200px;
  border: 1px solid;
}
.animated {
  animation: zoom 2s linear alternate infinite;
}
@keyframes zoom {
  to {
    transform: scale(1.25);
  }
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div>Moving Div!</div>
Run Code Online (Sandbox Code Playgroud)


注意:上述代码段中使用的动画仅是用于说明的示例.我在看到你的小提琴之前创造了它.Sammy慷慨地贡献了一个小提琴,以适应有问题的动画.看这里的小提琴.