小码哥的IT人生

animationend 事件

JavaScript基础 2022-06-08 11:55:06小码哥的IT人生shichen

animationend 事件

实例

当 CSS 动画结束时,对 <div> 元素做一些事情:

var x = document.getElementById("myDIV");
// 针对 Chrome、Safari 以及 Opera 的代码
x.addEventListener("webkitAnimationEnd", myEndFunction);
// 标准语法
x.addEventListener("animationend", myEndFunction);

完整实例:

<!DOCTYPE html>
<html>
<head>
<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() 方法将 "animationstart"、"animationiteration" 以及 "animationend" 事件附加到 DIV 元素。</p>
<div id="myDIV" onclick="myFunction()">点击我开始动画</div>
<script>
var x = document.getElementById("myDIV");
// Start the animation with 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", myRepeatFunction);
x.addEventListener("webkitAnimationEnd", myEndFunction);
// 标准语法
x.addEventListener("animationstart", myStartFunction);
x.addEventListener("animationiteration", myRepeatFunction);
x.addEventListener("animationend", myEndFunction);
function myStartFunction() {
  this.innerHTML = "animationstart event occured - The animation has started";
  this.style.backgroundColor = "pink";
}
function myRepeatFunction() {
  this.innerHTML = "animationiteration event occured - The animation was played again";
  this.style.backgroundColor = "lightblue";
}
function myEndFunction() {
  this.innerHTML = "animationend event occured - The animation has completed";
  this.style.backgroundColor = "lightgray";
}
</script>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

定义和用法

当 CSS 动画完成时发生 animationend 事件。

如需有关 CSS 动画的更多知识,请学习我们的 CSS3 动画教程

当 CSS 动画播放时,可能会发生三个事件:

  1. animationstart - 当 CSS 动画开始时发生
  2. animationiteration - 当 CSS 动画重复时发生
  3. animationend - 当 CSS 动画完成时发生

浏览器支持

表中的数字注明了完全支持该事件的首个浏览器版本。

数字后面的 "webkit" 或 "moz" 注明了使用前缀的首个版本。

事件 Chrome IE Firefox Safari Opera
animationend 4.0 webkit 10.0 16.0
5.0 moz
4.0 webkit 15.0 webkit
12.1

注释:对于 Chrome、Safari 以及 Opera,请使用 webkitAnimationEnd。

语法

object.addEventListener("webkitAnimationEnd", myScript);  // 针对 Chrome、Safari 以及 Opera 的代码
object.addEventListener("animationend", myScript);        // 标准语法

注释:Internet Explorer 8 或更早的版本不支持 addEventListener() 方法

技术细节

冒泡: 支持
可取消: 不支持
事件类型: AnimationEvent
DOM 版本: Level 3 Events

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024