如何在animate/scrolltop中添加“easing”

16

我正在使用以下功能创建滚动动画以锚定链接:

$('a').click(function(){
    $('html, body').animate(
        {scrollTop: $( $.attr(this, 'href') ).offset().top}, 
        500 );
    return false;
});

我想添加缓动效果,但是当我在“500”后添加“easing”时,脚本就出错了:

$('a').click(function(){
    $('html, body').animate(
        {scrollTop: $( $.attr(this, 'href') ).offset().top}, 
        500, easing );
    return false;
});

你有什么想法,我是做错了什么吗?


您可能有兴趣使用jquery.scrollTo插件:jquery.ScrollTo - Gramma2005
3
你在哪里定义了“easing”? 它应该是一个字符串。 - nullability
1个回答

35

首先需要引入jQuery.UI脚本,然后您的代码应该如下所示:

$('a').click(function(){
    var top = $('body').find($(this).attr('href')).offset().top;
    $('html, body').animate({
        scrollTop: top
    },500, 'easeOutExpo');

    return false;
});

供您参考:

缓动效果(Easing)

.animate()的剩余参数是一个字符串,用于命名所需使用的缓动函数。缓动函数指定了动画在不同点上的进行速度。jQuery库中仅提供两种缓动函数:默认的swing以及进度恒定的linear。通过插件可以使用更多的缓动函数,特别是jQuery UI套件。


为什么您的代码无法正常工作:

  1. 因为您使用的是animation方法范围内的this关键字,并引用了body和html对象。
  2. 因为easing不是一个方法,它是动画属性的字符串类型,您需要将其写成字符串形式,例如:'easeOutExpo'"easeOutExpo"

1
我得到了... #<Object>没有'easing'方法。 - user1444027
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/30363/discussion-between-woocash-and-user1444027 - WooCaSh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接