单击按钮重复动画

Stw*_*sch 5 javascript css animation css-animations

我想每次单击按钮时都重复动画。我尝试做这样的事情。

const dist = document.querySelector('.dist');

document.querySelector('button').addEventListener('click', () => {
  dist.classList.remove('animation');
  dist.classList.add('animation');
});
Run Code Online (Sandbox Code Playgroud)
.dist {
  width: 100px;
  height: 100px;
  background: black;
  margin-bottom: 30px;
}

.animation {
  transform: scale(1.5);
  transition: transform 3s;
}
Run Code Online (Sandbox Code Playgroud)
<div class="dist"></div>
<button type="button">Trigger Animation</button>
Run Code Online (Sandbox Code Playgroud)

但实际上,这段代码只执行了一次。

dist.classList.remove('animation');
dist.classList.add('animation');
Run Code Online (Sandbox Code Playgroud)

这部分不应该删除状态并从头开始动画吗?

Kev*_*Bot 2

班级变更正在分批进行。您应该请求一个动画帧来将类添加回元素:

window.requestAnimationFrame(function() {
    dist.classList.add('animation');
});
Run Code Online (Sandbox Code Playgroud)

window.requestAnimationFrame(function() {
    dist.classList.add('animation');
});
Run Code Online (Sandbox Code Playgroud)
const dist = document.querySelector('.dist');

document.querySelector('button').addEventListener('click', () => {
  dist.classList.remove('animation');
  window.requestAnimationFrame(function() {
    dist.classList.add('animation');
  });
});
Run Code Online (Sandbox Code Playgroud)
.dist {
  width: 100px;
  height: 100px;
  background: black;
  margin-bottom: 30px;
}

.animation {
  transform: scale(1.5);
  transition: transform 3s;
}
Run Code Online (Sandbox Code Playgroud)

requestAnimationFrame 的文档

查看更新的小提琴