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

如何让返回顶部按钮仅在桌面端显示(移动端隐藏)

解决方案

你可以通过两种方式实现「仅桌面端显示返回顶部按钮」的需求,核心是让JavaScript同时兼顾滚动距离和屏幕尺寸两个判断条件:

方案1:直接在滚动函数中判断窗口宽度

这种方式最简单,直接在控制按钮显示的逻辑里加入屏幕宽度判断,和现有滚动逻辑结合:

修改后的JavaScript代码:

let myButton = document.getElementById("to-top-container");

window.onscroll = function() {
  scrollFunction()
};

// 定义桌面端最小宽度(可根据需求调整,比如768px、1024px)
const DESKTOP_MIN_WIDTH = 768;

function scrollFunction() {
  const hasScrolledEnough = document.body.scrollTop > 25 || document.documentElement.scrollTop > 25;
  const isDesktop = window.innerWidth >= DESKTOP_MIN_WIDTH;

  // 同时满足「滚动超过25px」和「桌面端尺寸」才显示按钮
  if (hasScrolledEnough && isDesktop) {
    myButton.style.display = "block";
  } else {
    myButton.style.display = "none";
  }
}

// 监听窗口缩放事件,避免用户调整窗口时状态不更新
window.onresize = function() {
  scrollFunction();
};

方案2:使用window.matchMedia监听CSS媒体查询

如果你的CSS已经定义了桌面端媒体查询断点,用这种方式可以让JS和CSS的断点保持一致,避免重复维护数值:

修改后的JavaScript代码:

let myButton = document.getElementById("to-top-container");
// 匹配桌面端媒体查询(和CSS断点保持一致,比如min-width:768px)
const desktopMediaQuery = window.matchMedia('(min-width: 768px)');

window.onscroll = function() {
  updateButtonVisibility();
};

// 监听媒体查询变化(窗口缩放/设备旋转时触发)
desktopMediaQuery.addEventListener('change', updateButtonVisibility);

function updateButtonVisibility() {
  const hasScrolledEnough = document.body.scrollTop > 25 || document.documentElement.scrollTop > 25;
  const isDesktop = desktopMediaQuery.matches;

  if (hasScrolledEnough && isDesktop) {
    myButton.style.display = "block";
  } else {
    myButton.style.display = "none";
  }
}

// 初始化时执行一次,确保页面加载状态正确
updateButtonVisibility();

补充说明

  • 两种方案都需要处理窗口尺寸变化的情况,确保用户缩放窗口或切换设备横竖屏时,按钮状态能及时更新。
  • 可根据自己的响应式设计需求,调整min-width的数值(比如把768px改成1024px,适配你的桌面端定义)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:05:22