如何通过jQuery放慢滚动到顶部事件动画

How can Slow down scroll to top event by jQuery animate

本文关键字:顶部 事件 动画 滚动 何通过 jQuery      更新时间:2023-09-26

如何通过jQuery动画放慢滚动到顶部事件?

$('#go-to-top').click(function() {
   $(window.opera ? 'html' : 'html, body').animate({
      scrollTop: 0
    }, 80);
});

要减慢滚动速度,您可以增加完成动画所需的时间。目前,它需要 80 毫秒。如果将该数字更改为 1 秒,则可以看到差异:

$('#go-to-top').click(function () {
    $(window.opera ? 'html' : 'html, body').animate({
        scrollTop: 0
    }, 1000); // scroll takes 1 second
});

示例小提琴

如果您在页面中包含 jQueryUI 缓动库,也可以添加缓动效果。

下面是 animate 方法的文档。

您可以使用"持续时间"参数来更改动画

速度,也可以使用"缓动"参数提供一些自定义缓动函数来更改动画行为。

在您的情况下,您可以执行以下操作来指定动画"速度"。

$('#go-to-top').click(function() {
   $(window.opera ? 'html' : 'html, body').animate({
      scrollTop: 0,
   }, 1500); // 1500 here is the duration of animation in the milliseconds (seconds * 1000)
});

我还建议将window.opera替换为jQuery的$.browser.webkit,以获得更好的兼容性。请参阅文档。

像这样尝试,

$('#go-to-top').click(function() {
    $(window.opera ? 'html' : 'html, body').animate({
      scrollTop: 0
    },2000);// for 2 seconds
});