我可以使用JavaScript检测CSS关键帧动画中的百分比

时间:2016-07-20 11:33:50

标签: javascript css css-animations

我在想。我知道我可以通过侦听animationstart,animationiteration,animationend事件(显然我们在那里缺少浏览器前缀)来检测CSS动画何时开始,完成或重复,例如:

document.getElementById('identifier')
        .addEventListener("animationstart", function(){
          // do something...
        });

但是我想知道,是否有可能确定我们在运行CSS动画的位置,例如,当我们处于50%的关键帧动画时,我可以监听以下内容:

<!DOCTYPE html>
<html>
<head>
<style>
#animateDiv {
    width: 100px;
    height: 100px;
    background-color: red;
    position: relative;
    animation-name: example;
    animation-duration: 4s;
}

@keyframes example {
    0%   {background-color:red; left:0px; top:0px;}
    25%  {background-color:yellow; left:200px; top:0px;}
    50%  {background-color:blue; left:200px; top:200px;}
    75%  {background-color:green; left:0px; top:200px;}
    100% {background-color:red; left:0px; top:0px;}
}
</style>
</head>
<body>
<div id="animateDiv"></div>
<script>
// what do I do here? How do I listen for the 50% event of the keyframes?
document.getElementById('animateDiv').addEventListener('animation at 50%?', function() {
 console.log('got it');
})
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

埃洛,伙计。我不知道你是否可以从CSS动画中获得确切的关键帧,但你可以使用一些数学方法来获得它,就像我们的伙伴Paulie_D建议的那样。

在你的代码上,你的动画是4s长度,因此,关键帧50%的动画是在2s之后:

private static File traverse(File dir, String name) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; children != null && i < children.length; i++) {
            traverse(new File(dir, children[i]),name.trim());
        }
    }
    if (dir.isFile()) {
        if (dir.getName().trim().equalsIgnoreCase(name.trim())) {
            return dir;
        }
    }
return null;
}

你也可以使用(需要jQuery):

File leveldat = traverse(wftemp,"level.dat");

或者:

private static File traverse(File dir, String name) {
    System.out.println(dir.getAbsolutePath());
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; children != null && i < children.length; i++) {
            traverse(new File(dir, children[i]),name.trim());
        }
    }
    if (dir.isFile()) {
        if (ddir.getName().trim().equalsIgnoreCase(name.trim())) {
            System.out.println("We found a match: " + dir.getAbsolutePath());
            return dir;
        }
    }
return null;
}

我希望它能帮到你,伙计。