我正在使用以下函数创建滚动动画来锚定链接:
$('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.
为什么你的代码不起作用:
- 因为您使用了动画方法范围内的
this
并且 对body
和html
对象的引用。 - 因为
easing
不是一种方法。是一个字符串类型的动画属性所以你需要 将其写为字符串,例如:'easeOutExpo'
或"easeOutExpo"
。
关于jquery - 如何将 'easing' 添加到 animate/scrolltop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16680045/