单击某个按钮时如何激活动画?

时间:2020-04-03 23:35:26

标签: javascript html css animation dom-events


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
</head>
<body>
  <button id="button">Start Game</button>
  <img src="https://www.chelanfresh.com/wp-content/uploads/2018/11/apple.png" id="apple">

</body>
</html>

#button {
    min-width: 300px;
    min-height: 300px;
    color: #313133;
    }

#apple {
    height: 38%;
    width: 10%;
    margin-top: 27%;
    margin-left: 19%;
    visibility: hidden;
    animation-name: appleSlide;
    animation-duration: 3s; 
    animation-iteration-count: 1;
    animation-direction: normal;
    animation-play-state: paused;
    animation-delay: 1s; 
}

@keyframes appleSlide {
    0% {margin-left: -50%;}
    100% {margin-left: 19%}
}


let apple = document.getElementById("apple")
let button = document.getElementById("button")

function activateAnimations() {
    apple.style.animationPlayState = "running";
    apple.style.visibility = "visible";
  }

button.addEventListener("click", activateAnimations)

我的动画基本上是隐藏或不可见的,但是一旦用户单击按钮,图片就会出现并滑动到特定位置。香港专业教育学院一直在摆弄animationPlayState无济于事,动画永远不会激活。

1 个答案:

答案 0 :(得分:2)

  1. 您的代码中有些东西并没有真正的意义(例如apple.document.getElementById)。
  2. 您应该将苹果的原始位置添加到元素(不仅是动画关键帧)。
  3. 该按钮没有activateAnimations事件。

这是您的代码的修补程序:

window.addEventListener("load", function() {
  let apple = document.getElementById("apple")
  let button = document.getElementById("button")

  function activateAnimations() {
      apple.style.animationPlayState = "running";
      apple.style.visibility = "visible";
    }

  button.addEventListener("click", activateAnimations)
});
#button {
    min-width: 300px;
    min-height: 300px;
    color: #313133;
    }

#apple {
    height: 38%;
    width: 10%;
    margin-top: 27%;
    margin-left: -50%;
    visibility: hidden;
    animation-name: appleSlide;
    animation-duration: 3s; 
    animation-iteration-count: 1;
    animation-direction: normal;
    animation-play-state: paused;
    animation-delay: 1s; 
    animation-fill-mode: forwards;
}
@keyframes appleSlide {
    0% {margin-left: -50%;}
    100% {margin-left: 19%}
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
</head>
<body>
  <button id="button">Start Game</button>
  <img src="https://www.chelanfresh.com/wp-content/uploads/2018/11/apple.png" id="apple">

</body>
</html>