簡體   English   中英

單擊某個按鈕時如何激活 animation?

[英]How to activate an animation when a certain button is clicked?


<!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)

我的 animation 基本上是從隱藏或不可見開始的,但是一旦用戶單擊按鈕,圖片就會顯示並滑動到特定的 position。 我一直在擺弄 animationPlayState 無濟於事,animation 永遠不會激活。

  1. 您的代碼中有一些沒有意義的東西(例如apple.document.getElementById )。
  2. 您應該將蘋果的原始 position 添加到元素(不僅是動畫關鍵幀)。
  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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM