返回 jQuery 实例与特效代码列表
滚动与布局MIT兼容 jQuery 1.12 / 3.8 / 4.1

回到顶部按钮

页面滚动超过阈值后自动显现悬浮按钮,点击后平滑滚动回到顶部。

兼容性说明:使用 .animate({ scrollTop: 0 }),需完整版 jQuery(slim 版不含 animate)。

在线交互演示(独立沙箱)

$(function () {
  var $box = $('#btt-box');
  var $btn = $('#btt-btn');
  $box.on('scroll', function () {
    if ($box.scrollTop() > 80) $btn.fadeIn(180);
    else $btn.fadeOut(180);
  });
  $btn.on('click', function () {
    $box.stop(true).animate({ scrollTop: 0 }, 350);
  });
});
不用 jQuery 怎么写?(现代原生 JS / CSS 替代思路)

调用原生 window.scrollTo({ top: 0, behavior: 'smooth' }) 即可平滑回到顶部。

btn.addEventListener('click', () => container.scrollTo({ top: 0, behavior: 'smooth' }));