Javascript在滚动事件中使用requestAnimationFrame

6

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/

为什么这个动画运行不流畅?我的代码哪里出了问题?

谢谢!

1个回答

12

我认为动画看起来很流畅。

然而,你不应该在函数内调用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);

});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接