Javascript 在滚动事件上使用 requestAnimationFrame
Javascript using requestAnimationFrame on scroll event
我在scroll
事件中使用window.requestAnimationFrame
时遇到问题。
我想使用 CSS transform:translate3D
移动DIV
。
document.getElementById("content").addEventListener("scroll", function(){
var getScroll = this.scrollTop * 1.2;
function repeatOften() {
document.getElementById("moveable").style.transform =
"translate3D(0," + getScroll + "px, 0)";
requestAnimationFrame(repeatOften);
}
requestAnimationFrame(repeatOften);
});
这里有一个小提琴:https://jsfiddle.net/tcayv8dp/
为什么这个动画运行不流畅?我的代码有什么问题?
谢谢!
动画对我来说似乎很流畅。
但是,您不应该在函数中调用requestAnimationFrame
,因为这些调用将继续无休止地运行。
这就是我改进您的代码的方式:
// define the function outside the onscroll function so it doesn't get redefined
var getScroll;
function repeatOften() {
// use translateY instead of translate3D
document.getElementById("moveable").style.transform = "translateY(" + getScroll + "px)";
};
document.getElementById("content").addEventListener("scroll", function(){
getScroll = this.scrollTop * 1.2;
requestAnimationFrame(repeatOften);
});
相关文章:
- 没有找到相关文章