Detect specific CSS3 Keyframe with JavaScript

自古美人都是妖i 提交于 2019-12-06 16:39:32

Using the example Fiddle provided, what you're essentially looking to know is when the value of #sun element's bottom property is equal to 100px. You can do this by using getComputedStyle() to check that value, clearing the interval when it is equal to 100px and then executing whatever code you wish, like so:

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>

To check for multiple values, simply set a new interval. In the case of your example, the value of the bottom property should be 50px when the animation is 75% complete. That being said, it may not always be exactly 50px in every browser so, instead, given that we know the value of the bottom property will be decreasing at this point, instead check for it being less than or equal to 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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!