在点击事件上创建统一的滚动速度

时间:2014-05-12 20:56:21

标签: javascript jquery html css

让我们说我的网页上有很多不同领域的内容。

我想制作一个活动,以某个"率"将页面向下滚动到它。但是,我使用的方法似乎非常不一致。从导航栏滚动到几个像素的元素需要花费相同的时间,就像滚动到页面的最后一样

$('.slide-to').click(function() {
  $('html, body').animate({
    scrollTop: $($(this).data('element')).offset().top
  }, 2000);
});

如何修改它以制作"制服"滚动速度?

4 个答案:

答案 0 :(得分:1)

你必须使动画持续时间与你当前位置和你想要滚动的元素的位置之间的距离成比例,你可以试试这个:

$('.slide-to').click(function() {
  $('html, body').animate({
    scrollTop: $($(this).data('element')).offset().top
  }, Math.abs($($(this).data('element')).offset().top - this.offset().top) * 100);
});

答案 1 :(得分:1)

如果我理解正确,您需要修改持续时间(当前为2000毫秒)以反映需要滚动的像素数量。

$('.slide-to').click(function() {
    elemY = $($(this).data('element')).offset().top;
    pixels = Math.abs($(window).scrollTop() - elemY);
    pixelsPerMs = 10; 
    $('html, body').animate({
        scrollTop: elemY
    }, pixelsPerMs * pixels);
});

您可能还想更改动画的缓动功能。

答案 2 :(得分:1)

您可以使用$(this).data('element')).offset().top的值作为计时器值,然后将其乘以一个乘数,以获得您希望滚动设置为动画的每毫秒像素数。然后增加乘数以减慢动画。

$('.slide-to').click(function() {
  var multiplier = 10;
  $('html, body').animate({
    scrollTop: $($(this).data('element')).offset().top
  }, $(this).data('element')).offset().top * multiplier);
});

答案 3 :(得分:1)

你能够做到这一点,我已经创建了一个可以在这里找到的工作示例http://jsbin.com/jociy/3

如果你想知道,我也留下了一些评论,我认为代码是自我解释的,在这里:

$(document).ready(function(){

 // Say you're happy with scrolling 100px during 2secs
 var height = 100;
 var secs = 2000;

 // Calculate the ratio
 var ratio = (secs / height);

 // Now use the ratio to calculate new time according to container height
 var time = ratio * $(window).height();

 $('#scrollTo').on('click', function(){

    // get the element position that you want to scroll to
    var toPosition = $(".scrollTo").offset().top;

    // scroll to the element position
    $('html, body').animate({
      scrollTop: toPosition
    }, time, "linear");

 });

});

需要注意的一些事项,对于您想要实现的目标非常有用:

1)你可以通过测试给定距离的秒数来创建所需的速度,通过使用它作为参考,你可以找到你喜欢的速度。你决定最好的速度!

2)在这个例子中,我使用了“线性”缓动功能,为你保持一切清晰和基本。我会建议使用更整洁的东西,但同样,你可以随心所欲地控制它!

这就是全部!希望这会有所帮助:)

相关问题