在scroll事件上使用requestAnimationFrame的Javascript

时间:2016-03-15 17:07:48

标签: javascript html

window.requestAnimationFrame事件中使用scroll时遇到问题。

我想使用DIV

移动CSS transform:translate3D
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 个答案:

答案 0 :(得分:5)

动画对我来说似乎很顺利。

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

});