Javascript 动画间歇性触发

时间:2021-02-10 18:29:19

标签: javascript

我有一个带有计算正确答案的函数的数学游戏。如果用户回答正确,我想显示动画图像。我能够实现这一点,但它自己的动画基本上一次是,一次不是。

我错过了什么吗?

function checkAnswer() {

  // Checks the answer against the first element in 
  // the returned calculateCorrectAnswer array

  let userAnswer = parseInt(document.getElementById('answer-box').value);
  let calculatedAnswer = calculateCorrectAnswer();
  let isCorrect = userAnswer === calculatedAnswer[0];

  if(isCorrect) {
     incrementScore();
     moveRight();
    
  } else {
    alert(`Awwww .... you answered ${userAnswer}. the correct answer was ${calculatedAnswer[0]} ?`);
    incrementWrongAnswer();
  }

  runGame(calculatedAnswer[1]);
 
}


function moveRight() {
  let theImg = document.getElementById('myImg');
  let msg = document.getElementById('message');
  theImg.classList.toggle('fade-in');
  msg.classList.toggle('fade-in');
  
  
}

// My CSS

#myImg.fade-in {
  animation-name: fadeIn;               
    animation-duration: 2s;                 
    
}

@keyframes fadeIn {

  0% {opacity: 0;} 
    100% {opacity: 1;} 
}enter code here

2 个答案:

答案 0 :(得分:1)

在你的情况下,我会使用 transition,而不是 animation 代码看起来像这样:

#myImg {
  opacity: 0;
  transition: opacity 2s linear;
    
}
#myImg.fade-in {
  opacity: 1;
}

答案 1 :(得分:1)

找到解决方案,基本上只是删除类并再次添加:)

 function moveRight() {
  let theImg = document.getElementById('myImg');
  let msg = document.getElementById('message');
  theImg.classList.remove('fade-in');
  void theImg.offsetWidth; 
  theImg.classList.toggle('fade-in');
  msg.classList.remove('fade-in');
  void msg.offsetWidth; 
  msg.classList.toggle('fade-in');
  
  
}