You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现滚动停止时隐藏回到顶部按钮,滚动恢复时显示

修改后的回到顶部按钮代码(带滚动停止隐藏功能)

以下是整合了滚动超过300px才显示、滚动时显示/停止滚动后隐藏功能的完整代码:

/* Insert Top Button after Body Content */
$(function() {
  $('<button onclick="topFunction()" id="topBtn" title="Go to top"></button>').insertAfter('div#mw-content-text');
});

// 用于存储滚动定时器ID
let scrollTimer;

// 滚动事件处理
window.onscroll = function() {
  scrollFunction();
};

function scrollFunction() {
  const topBtn = document.getElementById("topBtn");
  const scrollTop = document.body.scrollTop || document.documentElement.scrollTop;

  if (scrollTop > 300) {
    // 滚动时显示按钮,并清除之前的隐藏定时器
    topBtn.style.display = "block";
    clearTimeout(scrollTimer);
    // 设置停止滚动2秒后隐藏按钮(可根据需求调整时间,单位毫秒)
    scrollTimer = setTimeout(() => {
      topBtn.style.display = "none";
    }, 2000);
  } else {
    // 滚动距离不足300px时直接隐藏按钮,并清除定时器
    topBtn.style.display = "none";
    clearTimeout(scrollTimer);
  }
}

// 点击按钮回到顶部
function topFunction() {
  window.scrollTo(0, 0);
}

关键改动说明

  • 添加滚动定时器:通过scrollTimer变量记录定时器ID,每次滚动时清除之前的定时器(避免重复触发隐藏),同时设置新的定时器——当用户停止滚动2秒后,自动隐藏按钮。你可以根据需求调整setTimeout的时间参数(比如改成1500就是1.5秒)。
  • 整合逻辑判断:先判断滚动距离是否超过300px,只有满足这个条件时才处理显示/隐藏的逻辑;否则直接隐藏按钮,避免无效操作。
  • 优化元素获取:在函数内只获取一次topBtn元素,减少DOM查询次数,提升性能。

内容的提问来源于stack exchange,提问作者greektranslator

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 08:10:40