的問題是,setInterval
設置爲12000
,但它需要24000
找回到頂部,所以setInterval
應該在24000
。
setInterval(function() {
$(".scrollballer").animate({ scrollTop: $(document).height() }, 12000);
setTimeout(function() {
$('.scrollballer').animate({scrollTop:0}, 12000);
},12000);
}, 24000); // <-- Don't run again until the full down/up cycle is complete
不過,也有更好的方法來做到這一點。改善這一點的第一步是對.animate
使用回調,而不是setTimeout
。
setInterval(function() {
// Use a callback to schedule the "up" animation-------------------------v
$(".scrollballer").animate({scrollTop:$(document).height()}, 12000, function() {
$('.scrollballer').animate({scrollTop:0}, 12000);
});
}, 24000);
下一步是要認識到內部.animate()
還可以接受一個回調,所以我們真的不需要setInterval()
。回調更好,因爲JS定時器並不完美,並且一個.animate()
可能在前一個完成之前開始。使用回調阻止了這一點。
// -----------v---create a named function that performs the down/up animations
(function down_then_up() {
$(".scrollballer").animate({scrollTop:$(document).height()}, 12000, function() {
// Use the `down_then_up` function as a callback----v--- to repeat the cycle
$('.scrollballer').animate({scrollTop:0}, 12000, down_then_up);
});
})(); // <-- invoke the `down_then_up` immediately to get it going.
所以我在這裏做一個叫做down_then_up
的函數來執行滾動頁面的循環。該函數在最後被()
立即調用。然後在回到頂端的內部.animate()
調用中,我將down_then_up
函數作爲回調函數。
編輯
的另一個問題是,當你向下滾動,你旅行的全部窗口的高度,即使它不是實際的圖像容器大。因此,如果窗口高度爲800
,jQuery將根據該數字進行計算,因此它認爲它需要在12秒內達到適當的速度。
然而,在上升階段,從目前的位置開始(這實際上是隻容器高度)和滾動高達0
,所以現在如果容器高度爲224
,jQuery的計算基於這個數字,這意味着它需要移動得更慢以在12秒內覆蓋更短的距離。
如果您根據容器高度而不是窗口設置滾動距離,則無論上升還是下降,它都會計算移動相同的距離,您將獲得均勻的速度。
你可以讓一個jsfiddle顯示你的問題?我不明白爲什麼它會從這個代碼上下滾動得更快...... – Alin 2014-12-07 16:59:47