在“Window”上执行“requestAnimationFrame”失败:作为参数1提供的回调不是一个函数。

11

我不确定我在这里做错了什么...

window.requestAnimFrame = function(){
return (
    window.requestAnimationFrame       || 
    window.webkitRequestAnimationFrame || 
    window.mozRequestAnimationFrame    || 
    window.oRequestAnimationFrame      || 
    window.msRequestAnimationFrame     || 
    function(/* function */ callback){
        window.setTimeout(callback, 1000 / 60);
    }
);
}();

function animationSequence(elem, ind) {
    this.ind = ind;
    this.elem = elem;
    this.distance = 450;
    this.duration = 900;
    this.increment = 0;
    this.start = Math.abs(this.ind)*450;
    var requestId = requestAnimFrame(this.animate);
    this.move();

    this.move = function() {
        this.elem.style.left = this.start - this.increment + "px";
    }
    this.animate = function() {
        var self = this;
        this.move();
        this.increment += 5;
        if (this.increment >= 450) { 
            if (this.ind == 0) { console.log("true"); this.elem.style.left = "1350px" }
            cancelAnimFrame(requestId);
        }
    }
    // this.animate();
}

你尝试过将 var requestId = requestAnimFrame(this.animate); 放在 this.animate 函数定义下面吗? - matewka
1个回答

35

如果我理解你的问题有误,请帮我纠正 - 你的问题是在 animate 方法中丢失了对 this 的引用,也就是说无法调用 this.move() 或增量递增?

如果是这样,请尝试这个方法 -

 var requestId = requestAnimFrame(this.animate.bind(this));

关于在requestAnimation回调中绑定this关键字的问题,请参见此处的答案。

还有这篇关于绑定的博客文章

更新于2019年5月

如果您可以使用ES6,可以使用箭头函数来保持作用域,如下所示:

let requestId = requestAnimFrame(() => { this.animate(); });

在这里阅读有关箭头函数的内容:

有关箭头函数和关键字this的博客文章


@BlinkingCahill 谢谢伙计,这对我也有用! - Nizar B.
你救了我的一天,伙计。 :) - Samrat Saha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接