2014-12-07 208 views
1

我想製作自動滾動條。它應該慢慢地滾動到底,然後慢慢地應該滾動到頂部,等等....滾動頂部,然後底部,然後頂部,然後底部

我寫了這個,

$(".scrollballer").animate({ scrollTop: $(document).height() }, 12000); 

setTimeout(function() { 
    $('.scrollballer').animate({scrollTop:0}, 12000); 
},12000); 

setInterval(function(){ 

$(".scrollballer").animate({ scrollTop: $(document).height() }, 12000); 

setTimeout(function() { 
    $('.scrollballer').animate({scrollTop:0}, 12000); 
},12000); 

},12000); 

然而,從頂部滾動至底部時,它滾動速度更快。如何使其速度相同?

+0

你可以讓一個jsfiddle顯示你的問題?我不明白爲什麼它會從這個代碼上下滾動得更快...... – Alin 2014-12-07 16:59:47

回答

1

的問題是,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秒內覆蓋更短的距離。

如果您根據容器高度而不是窗口設置滾動距離,則無論上升還是下降,它都會計算移動相同的距離,您將獲得均勻的速度。

+0

謝謝。是我嗎,還是更快一點? http://jsfiddle.net/gsmLrby2/ – user198989 2014-12-07 17:20:33

+1

@ user198989:我認爲問題在於您滾動的窗口高度超出了圖像容器的大小。所以,當它停下來的時候,它必須更快地移動到12秒內的全部距離(儘管它不需要一直走,jQuery不知道)。當它上升時,它會從當前位置移動到'0',所以它的距離較短,這意味着它會移動得更慢。相反,只需滾動「224」的容器高度即可。 http://jsfiddle.net/gsmLrby2/1/ – 2014-12-07 17:35:30

相關問題