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

移动端Scroll to top按钮触发后滚动卡顿问题求助

移动端Scroll to Top按钮滚动卡顿问题排查与修复

问题现象

添加了自动淡入的Scroll to top按钮,桌面端运行正常,但移动端点击激活后,页面滚动会卡在顶部。

相关代码

JavaScript代码

const scrollTop = function () {
  // 创建返回顶部按钮
  const scrollBtn = document.createElement("button");
  scrollBtn.innerHTML = "↑";
  scrollBtn.setAttribute("id", "scroll-btn");
  document.body.appendChild(scrollBtn);
  // 根据滚动距离显示/隐藏按钮
  const scrollBtnDisplay = function () {
    window.scrollY > window.innerHeight
      ? scrollBtn.classList.add("show")
      : scrollBtn.classList.remove("show");
  };
  window.addEventListener("scroll", scrollBtnDisplay);
  // 点击按钮滚动到顶部
  const scrollWindow = function () {
    if (window.scrollY != 0) {
      setTimeout(function () {
        window.scrollTo(0, window.scrollY - 50);
        scrollWindow();
      }, 10);
    }
  };
  scrollBtn.addEventListener("click", scrollWindow);
};
scrollTop(); scrollTop: scrolled;

CSS代码

section::after {
  content: "";
  display: table;
  clear: both;
}
#scroll-btn {
  opacity: 0;
  width: 60px;
  height: 60px;
  color: #fff;
  background-color: #c066c0;
  position: fixed;
  bottom: 10%;
  right: 10%;
  border: 2px solid #fff;
  border-radius: 50%;
  font: bold 40px monospace;
  transition: opacity 0.5s, transform 0.5s;
  overflow: hidden;
}
#scroll-btn.show {
  opacity: 1;
  transition: opacity 1s, transform 1s;
  overflow: hidden;
}

问题原因

移动端浏览器普遍存在**滚动回弹(overscroll)**特性:当页面滚动到顶部后,继续滑动页面会触发弹性滚动,此时window.scrollY会变成负数。而代码中判断条件是if (window.scrollY != 0),负数不等于0,导致递归调用scrollWindow永远不会停止,页面因此卡在顶部。桌面端没有这种滚动回弹行为,scrollY只会到0,递归能正常终止,所以运行正常。

另外,代码末尾的scrollTop: scrolled;是无效语法,属于冗余代码。

修复方案

方案1:调整判断条件兼容负数scrollY

把判断条件从window.scrollY != 0改为window.scrollY > 0,这样当scrollY变为负数时,递归自动停止:

const scrollWindow = function () {
  if (window.scrollY > 0) {
    setTimeout(function () {
      window.scrollTo(0, window.scrollY - 50);
      scrollWindow();
    }, 10);
  }
};

方案2:使用原生平滑滚动API(推荐)

直接利用浏览器原生的平滑滚动特性,代码更简洁,兼容性更好,还能避免手动递归的问题:

// 替换原来的scrollWindow函数
const scrollWindow = function () {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
};

同时记得删掉代码末尾的无效语句scrollTop: scrolled;。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:15:33