簡體   English   中英

滾動頂部,然后底部,然后頂部,然后底部

[英]Scroll top, then bottom, then top, then bottom

我想做一個自動卷軸。 它應緩慢滾動到底部,然后應緩慢滾動到頂部,依此類推。

我寫了這個

$(".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);

但是,從上到下滾動時,滾動速度更快。 如何使其保持相同的速度?

問題在於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()可以在前一個.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秒內覆蓋更短的距離。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM