JavaScript检测正在进行的CSS动画

JavaScript detect CSS animation in progress

本文关键字:CSS 动画 正在进行 检测 JavaScript      更新时间:2023-09-26

我的JavaScript在决定是否等待animationend事件时遇到了一些问题,我想知道是否存在解决此问题的优雅方案。

假设我有一个div,它在页面加载时设置动画并淡入,然后稍后我有另一个脚本,它将<img>标记附加到div。

我希望<img>在动画完成后附加,以避免动画过程中出现任何口吃,并使其看起来更好。

目前我知道我可以写这样的东西(假设我使用animate.css):

HTML:

<div class="append-image-here animated fadeIn"></div>

JavaScript:

$(function() {
  $('.append-image-here').one([
    'webkitAnimationEnd',
    'mozAnimationEnd',
    'MSAnimationEnd',
    'oanimationend',
    'animationend'
  ].join(' '), function() {
    $('<img>', { src: '/image.jpg' }).appendTo(this);
  });
});

如果脚本在动画完成和animationend事件触发之前运行,这是可以的,但如果脚本恰好在动画结束后运行,则<img>标记将永远不会创建,也永远不会附加到div(例如,如果处理程序设置为超时或类似于超过动画持续时间的超时)。

是否有任何方法可以检测CSS动画当前是否正在运行,以便脚本可以决定是否等待animationend,而不必依赖于用户添加的类或数据属性?

(我要求不要依赖类和属性,因为如果我使用别人的动画,我可能不会提前知道类)

如有任何帮助,我们将不胜感激。

为什么不在文档上使用.on(),甚至检查哪个动画finished和哪个元素已设置动画(e.target)事件处理程序将在DOM完全加载和CSS动画启动之前附加。

演示:JSnippet演示

注意:DOM就绪时不要附加-$(function(){ ... })

$(document).on([
    'webkitAnimationEnd',
    'mozAnimationEnd',
    'MSAnimationEnd',
    'oanimationend',
    'animationend'
    ].join(' '), function(e) {
       //Do whatever you want 
       console.log(e);
       $('ul').append(
          "<li>Animation end detected on: "  
          + e.target 
          + "." + e.target.className + 
          "</li>"
       );
});

$(function(){
  
    $('button').click(function(){
        $(this).addClass('animate');
    });
    
});
$(document).on([
    'webkitAnimationEnd',
    'mozAnimationEnd',
    'MSAnimationEnd',
    'oanimationend',
    'animationend'
  ].join(' '), function(e) {
    //Do whatever you want 
    console.log(e);
    $('ul').append(
        "<li>Animation end detected on: "  
        + e.target 
        + "." + e.target.className + 
        "</li>"
    );
    $('button').removeClass('animate');
});
button {
        width: 300px;
        background-color: red;
}
button.animate {
        -webkit-animation-name: example; /* Chrome, Safari, Opera */
        -webkit-animation-duration: 1s; /* Chrome, Safari, Opera */
        animation-name: example;
        animation-duration: 1s;
}
/* Chrome, Safari, Opera */
@-webkit-keyframes example {
    from {background-color: red;}
    to {background-color: yellow;}
}
/* Standard syntax */
@keyframes example {
    from {background-color: red;}
    to {background-color: yellow;}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="animate">Trigger animation</button>
<ul></ul>