如何为动画/滚动顶部添加'缓动'

use*_*027 14 jquery

我使用以下函数创建一个滚动动画来锚定链接:

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

我想补充一下.但是,当我在'500'之后添加'easing'时,会破坏脚本:

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

我有什么想法我做错了吗?

Woo*_*aSh 35

首先你需要包含jQuery.UI脚本然后你的代码应该看起来:

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

    return false;
});
Run Code Online (Sandbox Code Playgroud)

供您参考:

缓解

.animate()的其余参数是一个命名要使用的缓动函数的字符串.缓动函数指定动画在动画中的不同点处进行的速度.jQuery库中唯一的缓动实现是默认的,称为swing,以及一个以恒定速度进行的实现,称为线性.使用插件可以使用更多的缓动函数,尤其是jQuery UI套件.


为什么你的代码不工作:

  1. 因为你使用的this是动画方法的范围和引用bodyhtml对象.
  2. 因为easing不是一种方法.是字符串类型的动画属性,因此您需要将其写为字符串,例如:'easeOutExpo'"easeOutExpo".

  • 这不起作用,它现在不滚动 (2认同)