首页 > 解决方案 > 在 JavaScript 对象中制作重复动画循环

问题描述

我想将动画循环排序为 JavaScript 中的对象。对象的功能会是这样的

var a; var move = new Repeat(10,function(){a++}); 它会以动画速度运行,而不是立即运行。

这是我的原始代码(不起作用)。

        function obj(id){return document.getElementById(id);}
        function Repeat(fn,rpt){
            this.function = fn;
            this.repeat = rpt;
            this.counter = 0;
            this.id=setInterval(this.start,5);
            this.start = function(){
                if (this.counter == this.repeat) {
                    clearInterval(id);
                } else {
                    this.repeat++;
                    this.function();
                }
            }
        }


        var box = obj('animation');
        var a=0;
        var move = new Repeat(function(){
            a++;
            box.style.top=a+'px';
            box.style.left=a+'px';
        },300);
        move.start();

因此,我正在寻找实现这一目标的建议。

标签: javascriptjsoncss-animations

解决方案


也许您可以使用 Web Animations API 来做到这一点,我想这会更容易https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API


推荐阅读