我想平滑地向下滚动。我不想为此写一个函数——特别是如果jQuery已经有了一个。
当前回答
跨浏览器代码是:
$(window).scrollTop(300);
它没有动画,但在任何地方都适用
其他回答
如果你想在页面的末尾向下移动(所以你不需要向下滚动到底部),你可以使用:
$('body').animate({ scrollTop: $(document).height() });
尼克的回答很管用。在animate()调用中指定complete()函数时要小心,因为它将被执行两次,因为你声明了两个选择器(html和body)。
$("html, body").animate(
{ scrollTop: "300px" },
{
complete : function(){
alert('this alert will popup twice');
}
}
);
下面是避免双重回调的方法。
var completeCalled = false;
$("html, body").animate(
{ scrollTop: "300px" },
{
complete : function(){
if(!completeCalled){
completeCalled = true;
alert('this alert will popup once');
}
}
}
);
尼克的回答很好,默认设置也很好,但你可以通过完成所有可选设置来更全面地控制滚动。
下面是它在API中的样子:
.animate( properties [, duration] [, easing] [, complete] )
所以你可以这样做:
.animate(
{scrollTop:'300px'},
300,
swing,
function(){
alert(animation complete! - your custom code here!);
}
)
这是jQuery .animate函数的api页面:http://api.jquery.com/animate/
但如果你真的想在滚动时添加一些动画,你可以试试我的简单插件(AnimateScroll),它目前支持30多种easing样式
在其他例子中,动画总是从页面刷新后的页面顶部开始。
我通过不直接动画css来修复这个问题,而是调用window.scrollTo();每一步:
$({myScrollTop:window.pageYOffset}).animate({myScrollTop:300}, {
duration: 600,
easing: 'swing',
step: function(val) {
window.scrollTo(0, val);
}
});
这也解决了html vs body的问题,因为它使用跨浏览器的JavaScript。
关于jQuery的animate函数的更多信息,请访问http://james.padolsey.com/javascript/fun-with-jquerys-animate/。