jQuery 如何将“缓动”添加到动画/滚动顶部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16680045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:34:42  来源:igfitidea点击:

How to add 'easing' to animate/scrolltop

jquery

提问by user1444027

I am using the following function to create a scroll animation to anchor links:

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

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

I would like to add easing. However, when I add 'easing' after '500' it breaks the script:

我想添加缓动。但是,当我在“500”之后添加“缓动”时,它会破坏脚本:

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

Any ideas what I am doing wrong?

任何想法我做错了什么?

回答by WooCaSh

First you need include jQuery.UI script then your code should look:

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

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

    return false;
});

For your information:

供您参考:

Easing

宽松

The remaining parameter of .animate() is a string naming an easing function to use. An easing function specifies the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UIsuite.

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



Why your code not working:

为什么你的代码不起作用:

  1. Because you use thiswhich was in scope of animation method and reference to bodyand htmlobjects.
  2. Because easingis not a method. Is a string type of animation property so you need write it as string for example: 'easeOutExpo'or "easeOutExpo".
  1. 因为您使用的this是动画方法范围内的 which 并引用bodyhtml对象。
  2. 因为easing不是方法。是字符串类型的动画属性,因此您需要将其写为字符串,例如:'easeOutExpo'"easeOutExpo"