javascript 无法在“窗口”上执行“requestAnimationFrame”:作为参数 1 提供的回调不是函数。
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22039180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Failed to execute 'requestAnimationFrame' on 'Window': The callback provided as parameter 1 is not a function.
提问by natecraft1
Not sure what I'm doing wrong here...
不知道我在这里做错了什么......
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();
}
回答by BlinkingCahill
Ok so help me out if I'm getting you wrong - is your problem that you have lost your reference to this
within the animate method? i.e. you can't call this.move()
or increment the increment?
好的,如果我弄错了,请帮助我 - 您的问题是this
在 animate 方法中丢失了参考吗?即您不能调用this.move()
或增加增量?
If so try this-
如果是这样试试这个 -
var requestId = requestAnimFrame(this.animate.bind(this));
See this answer about binding with requestAnimation callbacks here.
在此处查看有关使用 requestAnimation 回调进行绑定的答案。
And this blog post on binding.
还有这篇关于 binding 的博客文章。
Update May 2019
2019 年 5 月更新
If you can use ES6 you can employ an arrow function, which will maintain scope like this:
如果你可以使用 ES6,你可以使用一个箭头函数,它会保持这样的作用域:
let requestId = requestAnimFrame(() => { this.animate(); });
Read about arrow functions here:
在此处阅读箭头函数: