【问题标题】:Failed to execute 'requestAnimationFrame' on 'Window': The callback provided as parameter 1 is not a function.无法在“窗口”上执行“requestAnimationFrame”:作为参数 1 提供的回调不是函数。
【发布时间】:2014-03-29 03:37:06
【问题描述】:

不知道我在这里做错了什么......

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 函数定义的下方?

标签: javascript animation requestanimationframe


【解决方案1】:

好的,如果我弄错了,请帮助我 - 您的问题是您在 animate 方法中丢失了对 this 的引用吗?即您不能调用this.move() 或增加增量?

如果是这样试试这个-

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

请参阅有关与 requestAnimation 回调 here 绑定的答案。

还有这个blog post on binding

2019 年 5 月更新

如果你可以使用 ES6,你可以使用箭头函数,它会像这样保持范围:

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

在此处了解箭头功能:

Blog post about arrow functions and the keyword this

【讨论】:

  • @BlinkingCahill 谢谢伙计,它也对我有用!
  • 你救了我的好朋友。 :)
猜你喜欢
  • 2020-12-22
  • 2019-12-11
  • 2017-12-27
  • 1970-01-01
  • 1970-01-01
  • 2022-06-23
  • 1970-01-01
  • 2023-03-04
  • 2018-04-01
相关资源
最近更新 更多