使用JavaScript检测特定的CSS3关键帧

时间:2016-07-29 07:44:16

标签: javascript css3 css-animations

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

这就是我的尝试:

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

但它仅支持animationstart,animationiteration和animationend。

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

1 个答案:

答案 0 :(得分:2)

使用提供的示例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;
    }
}
<div id="sun"></div>

相关问题