滚动顶部,然后是底部,然后是顶部,然后是底部

时间:2014-12-07 16:56:33

标签: javascript jquery

我想制作一个自动滚动条。它应该慢慢滚动到底部,然后慢慢滚动到顶部,所以......

我写过这个,

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

但是,从上到下滚动时滚动速度更快。如何使速度相同?

1 个答案:

答案 0 :(得分:1)

问题是setInterval设置为12000,但需要24000才能返回到顶部,因此setInterval应该位于24000 1}}。

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,所以现在如果容器高度为{ {1}},jQuery根据该数字计算,这意味着它需要更慢地移动以在12秒内覆盖更短的距离。

如果您根据容器高度而不是窗口设置要滚动的距离,则无论是向上还是向下,它都会计算移动相同的距离,并且您将获得均匀的速度。