碰到的問題:在第一次點擊實現動畫結束后,再點擊無法實現動畫;
解決:動畫結束后要清除元素的動畫屬性;
x.style.WebkitAnimation = ""; // Chrome, Safari 和 Opera 代碼
x.style.animation = "";
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</title>
<style>
#myDIV {
margin: 25px;
width: 550px;
height: 100px;
background: orange;
position: relative;
font-size: 20px;
}
/* Chrome, Safari, Opera */
@-webkit-keyframes mymove {
from {top: 0px;}
to {top: 200px;}
}
@keyframes mymove {
from {top: 0px;}
to {top: 200px;}
}
</style>
</head>
<body>
<p>該實例使用了 addEventListener() 方法為 DIV 元素添加"animationstart", "animationiteration" 和 "animationend" 事件。</p>
<div id="myDIV" onclick="myFunction()">點我開始動畫</div>
<script>
var x = document.getElementById("myDIV")
// 使用 JavaScript 開始動畫
function myFunction() {
x.style.WebkitAnimation = "mymove 4s 2"; // Chrome, Safari 和 Opera 代碼
x.style.animation = "mymove 4s 2";
}
// Chrome, Safari 和 Opera
x.addEventListener("webkitAnimationStart", myStartFunction);
x.addEventListener("webkitAnimationIteration", myIterationFunction);
x.addEventListener("webkitAnimationEnd", myEndFunction);
x.addEventListener("animationstart", myStartFunction);
x.addEventListener("animationiteration", myIterationFunction);
x.addEventListener("animationend", myEndFunction);
function myStartFunction() {
this.innerHTML = "animationstart 事件觸發 - 動畫已經開始";
this.style.backgroundColor = "pink";
}
function myIterationFunction() {
this.innerHTML = "animationiteration 事件觸發 - 動畫重新播放";
this.style.backgroundColor = "lightblue";
}
function myEndFunction() {
this.innerHTML = "animationend 事件觸發 - 動畫已經完成";
this.style.backgroundColor = "lightgray";
x.style.WebkitAnimation = ""; // Chrome, Safari 和 Opera 代碼
x.style.animation = "";
}
</script>
</body>
</html>