首页 > 解决方案 > 使用javascript在每次点击时触发动画

问题描述

我正在尝试使用 CSS 动画翻转卡片。现在它可以工作,但只能在第一次单击按钮时使用。本质上,我的用例是:点击按钮,翻转卡片。点击按钮,翻转卡片等。

function nextCard(){
    document.getElementById('card').addEventListener("click",flipTheCard());
}

function flipTheCard(){
    document.getElementById('card').classList.add('newCard');
}

动画通过向卡片添加一个类来工作。

.newCard {
  animation: flip 1.5s;
  transform-origin: 50% 100% 0;
}

我已经尝试在动画之后删除该类并在每次单击时重新添加它,但这只是让它完全停止工作。

有什么想法或更好的方法吗?不确定添加和删除动画类是否是最佳实践。

谢谢!

标签: javascripthtmlcssanimation

解决方案


只需用您的代码替换它,它就会正常工作(您期望它的工作方式)

const card = document.getElementById('card')
function nextCard(){
 card.addEventListener("click",flipTheCard);
}

function flipTheCard(){ 
  card.classList.add('newCard');
  setTimeout(()=> {
    card.classList.remove('newCard')
  },1500)
}

以下是反映您的问题的小例子

const btn = document.querySelector('.btn')

const box = document.querySelector('.box')

btn.addEventListener('click', () => {
  box.classList.add('animate')
  
  setTimeout(() => {
    box.classList.remove('animate')
  },1500)
})
.box{
  width: 100px;
  height: 100px;
  background-color: blue;
  margin: auto;
  margin-top: calc(100vh - 60vh);
}

.box.animate{
    animation: spin 1.5s forwards;
}

@keyframes spin{
  0%{
    transform: rotate(0deg);
  }
  100%{
    transform: rotate(360deg);
  }
}
  <div class='box'></div>
  
  <button class="btn">click</button>
还要回答“如果添加和删除动画类是最佳实践”,这样做没有害处。


推荐阅读