javascript - 无法在 'requestAnimationFrame' : The callback provided as parameter 1 is not a function. 上执行 'Window'

标签 javascript animation requestanimationframe

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

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();
}

最佳答案

好的,如果我误会了,请帮帮我——你的问题是你在 animate 方法中丢失了对 this 的引用吗?也就是说,您不能调用 this.move() 或增加 increment?

如果是这样试试这个-

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

请参阅有关与 requestAnimation 回调绑定(bind)的答案 here .

还有这个blog post on binding .

2019 年 5 月更新

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

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

在这里阅读箭头函数:

Blog post about arrow functions and the keyword this

关于javascript - 无法在 'requestAnimationFrame' : The callback provided as parameter 1 is not a function. 上执行 'Window',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22039180/

相关文章:

ios - 我可以为 NSAttributedString 的大小||颜色设置动画吗?

android - 3D旋转-透视

javascript - requestAnimationFrame [now] 与 performance.now() 时间差异

javascript - 将 requestAnimationFrame 分配给对象变量时出现类型错误

javascript - Google Closure 编译器不压缩字符串值?

javascript - 战舰游戏: Allowing hits to be registered on ships with lengths other than 4

javascript - Highcharts饼图切片动画仅在抛出错误时起作用

javascript - 我想在调用 Office.context.ui.displayDialogAsync() 方法时跳过显示消息

javascript - 连接时更新 firebase 中的用户配置文件

javascript - Websocket 连接在 Safari iOS 中随机挂起