jquery - 如何将 'easing' 添加到 animate/scrolltop

标签 jquery

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

$('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.UI 脚本,然后您的代码应如下所示:

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

    return false;
});

供您引用:

宽松

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 UI suite.

<小时/>

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

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

关于jquery - 如何将 'easing' 添加到 animate/scrolltop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16680045/

相关文章:

javascript - 仅使用文本和数字将 div 中的文本包裹起来

javascript - 如果更改输入值,jQuery 提交表单

javascript - 使用 Requirejs 的非 AMD 库

jquery - main.js 上的谷歌地图 "a is null"(第 1121 行)

javascript - 单页应用程序中的历史记录.pushState/后退按钮/导航

javascript - 如何在内部 html 中获取特定类

javascript - 如何使用 Jquery-Chosen 插件使第一个选项成为下拉列表中的默认值

javascript - 使用 JQuery 选择名称中包含多个点的输入标签

jquery - 我有一个函数在调用媒体查询时仍在影响 div 的位置,我想停止它

jquery - 使用 jQuery 更改任何单击的 block 元素内的文本颜色