【问题标题】:Detect specific CSS3 Keyframe with JavaScript使用 JavaScript 检测特定的 CSS3 关键帧
【发布时间】:2016-07-29 19:32:26
【问题描述】:

如何检测动画到达特定关键帧? (例如 50% 或 75%)。

这是我尝试过的:

element.addEventListener("animationend", AnimationListener, false);

但它只支持animationstart、animationiteration和animationend。

http://jsfiddle.net/W3y7h/294/

【问题讨论】:

  • 据我所知,唯一的选择是使用计时器并使用您自己的计算。刚刚检查了规格,似乎有一个elapsedTime 属性,但它仍然只会告诉你时间,它代表的百分比仍然需要计算。
  • 请提供一个你的动画示例。
  • @Shaggy 你检查过小提琴吗?
  • @Beckham:抱歉,不知道我怎么错过了!
  • css-tricks.com/… 有一些有用的见解。

标签: javascript css css-animations


【解决方案1】:

使用提供的 Fiddle 示例,您实际上想知道的是 #sun 元素的 bottom 属性的值何时等于 100px。您可以通过使用getComputedStyle() 检查该值来执行此操作,当它等于100px 时清除间隔,然后执行您希望的任何代码,如下所示:

var style=window.getComputedStyle(document.getElementById("sun")),
	interval=setInterval(function(){
        if(parseInt(style.getPropertyValue("bottom"))===100){
            clearInterval(interval);
            console.log("50% reached");
        }
    },1);
#sun{
    animation:sunrise 1s ease;
    bottom:0;
    background:#ff0;
    border-radius:50%;
    height:50px;
    position:absolute;
    width:50px;
}
@keyframes sunrise{
    0%{
        bottom:0;
        left:0;
    }
    50%{
        bottom:100px;
    }
    100%{
        bottom:0;
        left:400px;
    }
}
<div id="sun"></div>

要检查多个值,只需设置一个新的间隔。在您的示例中,当动画完成 75% 时,bottom 属性的值应为 50px。话虽如此,它可能并不总是在每个浏览器中都完全是 50px,因此,鉴于我们知道 bottom 属性的值此时将减少,而是检查它是否小于或等于 50 :

var style=window.getComputedStyle(document.getElementById("sun")),
	interval=setInterval(function(){
        if(parseInt(style.getPropertyValue("bottom"))===100){
            clearInterval(interval);
            console.log("50% reached");
            interval=setInterval(function(){
                if(parseInt(style.getPropertyValue("bottom"))<=50){
                    clearInterval(interval);
                    console.log("75% reached");
                }
            },1);
        }
    },1);
#sun{
    animation:sunrise 1s ease;
    bottom:0;
    background:#ff0;
    border-radius:50%;
    height:50px;
    position:absolute;
    width:50px;
}
@keyframes sunrise{
    0%{
        bottom:0;
        left:0;
    }
    50%{
        bottom:100px;
    }
    100%{
        bottom:0;
        left:400px;
    }
}
&lt;div id="sun"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多