【问题标题】:JavaScript detect CSS animation in progressJavaScript 检测正在进行的 CSS 动画
【发布时间】:2015-09-15 18:03:23
【问题描述】:

我的 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 事件触发,这很好,但如果脚本恰好在动画结束后运行,&lt;img&gt; 标记将永远不会被创建并且永远不会被附加到 div (例如,如果处理程序设置为超时或超过动画持续时间的类似设置)。

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

(我要求不要依赖类和属性,因为如果我正在使用其他人的动画,我可能无法提前知道类)

任何帮助将不胜感激。

【问题讨论】:

标签: javascript jquery html css animation


【解决方案1】:

为什么不在文档上使用.on(),甚至检查哪个动画刚刚 完成以及哪个元素被动画化了 (e.target) 事件处理程序将在 DOM 完全加载并触发 CSS 动画之前附加。

演示:JSnippet Demo

注意:当 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>

【讨论】:

  • 有趣的是,有时我们看不到明显的东西。它一直就在我面前;一开始我没有想到这一点,我感到有点尴尬:)
  • 这件事一直发生在我身上(过度思考)......但这是一个可以帮助他人的好问题,玩得开心。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 2012-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多