javascript - 检测链式动画集的 "animationend"事件

标签 javascript jquery css

这是我的CSS,其中三个关键帧绑定(bind)在一起做一个链式动画

#anim-div{
    -webkit-animation-name    : mpbar-anim-page1, mpbar-anim-page2, mpbar-anim-page3;
    animation-name            : mpbar-anim-page1, mpbar-anim-page2, mpbar-anim-page3;
    -webkit-animation-delay   : 0s, 0.7s, 1.4s;
    animation-delay           : 0s, 0.7s, 1.4s;
    -webkit-animation-duration: 0.7s;
    animation-duration        : 0.7s;
}

是否可以检测整个集合的animationend事件?
当我尝试时,它会检测每个关键帧的 animationend(最终触发 3 个事件)

最佳答案

假设动画的数量未知,最终动画的名称也未知,您可以使用 getComputedStyle 来实现。将动画读入数组。然后,当 animationend 事件触发时,递增一个变量并在该变量的值等于数组长度时执行您希望的代码,如下所示:

var div=document.querySelector("div"),
    style=window.getComputedStyle(div),
    animation=style.getPropertyValue("animation-name")||style.getPropertyValue("-moz-animation-name")||style.getPropertyValue("-webkit-animation-name"),
//  Delete unneeded prefixed properties above 
    count=animation?animation.split(",").length:0,
    ended=0;
div.addEventListener("animationend",function(){
  ended++;
  if(ended===count){
//  Your code here
    console.log(ended+" animations completed.");
  }
},0);
div{
  animation:x 1s ease-in-out,y 1s ease-in-out 1s,z 1s ease-in-out 2s;
  background:#000;
  height:50px;
  width:50px;
}
@keyframes x{to{transform:rotatex(180deg);}}
@keyframes y{to{transform:rotatey(180deg);}}
@keyframes z{to{transform:rotatez(180deg);}}
/* Housekeeping */
body,html{height:100%;}
body{align-items:center;display:flex;justify-content:center;}
<div></div>

关于javascript - 检测链式动画集的 "animationend"事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37062897/

相关文章:

php - jQuery,在 ul 中 foreach div

javascript - RTCDataChannel 信号?

javascript - AngularJS - 如何恢复选择中的选定选项

jquery - 通过 jQuery 和 Spring Boot 创建简单的注册表单

javascript - 转到顶部按钮在 Firefox 浏览器中不起作用

html - :active selector of <a> tag without href attribute

javascript - 如何捕捉 div 位置并稍后重新定位(在 MAC 上)

html - 媒体查询将标题移动到图像右侧

javascript - 使用 jQuery 时如何在 ASP.NET 中同时触发 OnClick 和 OnClientClick 事件?

javascript - 使用动态键值对创建数组