requestAnimationFrame 不等待下一帧
requestAnimationFrame not waiting for the next frame
感谢入住!
据我所知(可能是错误的)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 方法(有点)像 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); }); };
但我必须承认,我的答案还没有完全研究,如果有人能找到更好的信息,我也会很感激。