使用requestAnimationFrame on scroll事件的Javascript
在使用requestAnimationFrame on scroll事件的Javascript,javascript,html,Javascript,Html,在滚动事件上使用窗口.requestAnimationFrame时出现问题 我想使用CSS transform:translate3D移动DIV document.getElementById("content").addEventListener("scroll", function(){ var getScroll = this.scrollTop * 1.2; function repeatOften() { document.getE
滚动
事件上使用窗口.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);
});
这是一把小提琴:
为什么这个动画运行不平稳?我的代码有什么问题
谢谢大家! 动画在我看来很流畅 但是,您不应该在函数内部调用
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);
});