2016-03-15 50 views
2

scroll事件中使用window.requestAnimationFrame時出現問題。JavaScript在滾動事件上使用requestAnimationFrame

我想用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); 

}); 

檢查這個小提琴移動DIVhttps://jsfiddle.net/tcayv8dp/

爲什麼這個動畫不流暢運行?

我的代碼有什麼問題?

謝謝.....。 。

回答

4

動畫對我來說很順利。

但是,您不應該在函數內部調用​​,因爲這些調用將不斷運行。

這是我會怎麼提高代碼:

// 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); 

});