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

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

本文介绍了使用JavaScript检测特定的CSS3关键帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to detect that the animation reached a specific keyframe? (For example 50% or 75%).

这是我试过的:

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

但它仅支持animationstart,animationiteration和animationend。

but it supports animationstart, animationiteration and animationend only.

推荐答案

使用Fiddle提供的示例,您基本上要知道的是 #sun 元素的底部属性等于 100px 。您可以使用检查该值,清除等于 100px 的间隔,然后执行您希望的任何代码,如下所示:

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>

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

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>

这篇关于使用JavaScript检测特定的CSS3关键帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 11:07