感谢签到!
据我所知(这可能是错误的)JavaScript 的 requestAnimationFrame 方法(有点)像 setTimeout 一样工作,除了它不等待一定的时间而是等待下一帧被渲染。
这可以用于很多事情,但我在这里试图实现的是基于 CSS 的 JavaScript 控制的淡入淡出效果。 下面是带有解释的代码:
//This line makes the element displayed as block from none
//but at this point it has an opacity value of 0
this.addClass('element__displayed');
//here i am waiting a frame so that the previously added
//display value takes effect
window.requestAnimationFrame(function(){
//adding opacity: 1 for fade effect
this.addClass('element__visible');
}.bind(this));
我的问题是,即使该元素设置了 css 过渡,并且我正在等待显示值被渲染,但我没有得到任何过渡,它只是弹出。
(如果我使用 setTimeout(..., 1000/60),它会起作用,但与 requestAnimationFrame 相比,setTimeout 是一个性能瓶颈)
请不要尝试为淡入淡出效果提供替代解决方案,因为我的问题不是效果,而是为什么 animationFrame 不工作!
谢谢!
最佳答案
我认为 requestAnimationFrame 不能保证等待下一帧。 Paul Irish writes
Any rAFs queued in your event handlers will be executed in the same frame. Any rAFs queued in a rAF will be executed in the next frame.
如果改编了您的演示,它现在适用于我的 Chrome:https://jsfiddle.net/ker9zpjs/
我曾经在我的工具箱里找到过这个助手:
var nextFrame = function(fn) { raf(function() { raf(fn); }); };
但我必须承认,我的答案没有经过充分研究,如果有人能找到更好的信息,我也将不胜感激。
关于javascript - requestAnimationFrame 不等待下一帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38631302/