2014-12-07 211 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

相关问题