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

JS实现的滚动显示模块如何在距页面底部300px位置自动隐藏?

问题原因

你的代码存在4个核心问题:

  • 变量赋值错误:alert() 方法返回值为 undefined,你将弹窗操作和变量赋值写在一起,导致 endPageHeight 实际为 undefined,后续判断条件永远不成立。
  • 阈值计算逻辑错误:window.scrollY 代表滚动条从顶部滚动的距离,最大值为 页面总高度 - 视口高度,直接用 页面总高度 - 300 作为隐藏阈值,永远无法达到触发条件。
  • 高度计算时机错误:仅在页面初始化时获取一次页面总高度,后续页面内容动态更新、高度变化时,保存的高度值就会失效。
  • 判断顺序错误:优先判断 scrollY > 1000 的显示条件,哪怕已经滚动到底部隐藏区域,也会优先命中显示逻辑,隐藏分支永远不会执行。

修正后的代码

const navShareLink = document.getElementById('navShareLink');

document.addEventListener('scroll', function(e) {
  // 每次滚动重新计算页面参数,适配动态高度页面
  const pageTotalHeight = document.documentElement.scrollHeight;
  const viewportHeight = window.innerHeight;
  // 距离底部300px时触发隐藏的阈值
  const hideThreshold = pageTotalHeight - viewportHeight - 300;
  const isWideScreen = window.innerWidth > 576;

  // 优先判断是否进入底部隐藏区域
  if (isWideScreen && window.scrollY > hideThreshold) {
    navShareLink.style.display = "none";
  } 
  // 再判断是否满足显示条件
  else if (isWideScreen && window.scrollY > 1000) {
    navShareLink.style.display = "block";
  } 
  // 其他情况统一隐藏
  else {
    navShareLink.style.display = "none";
  }
});

优化建议

如果页面存在频繁的动态内容加载,你可以将页面高度计算逻辑抽离,在内容加载完成、窗口尺寸变化时再重新计算,减少滚动事件中的计算量:

const navShareLink = document.getElementById('navShareLink');
let hideThreshold = 0;
let isWideScreen = window.innerWidth > 576;

// 统一更新页面参数的方法
function updatePageParams() {
  const pageTotalHeight = document.documentElement.scrollHeight;
  const viewportHeight = window.innerHeight;
  hideThreshold = pageTotalHeight - viewportHeight - 300;
  isWideScreen = window.innerWidth > 576;
}

// 页面初始化、窗口尺寸变化时调用更新
window.addEventListener('load', updatePageParams);
window.addEventListener('resize', updatePageParams);
// 如果有自定义的内容加载完成事件,也可以监听后调用 updatePageParams()

document.addEventListener('scroll', function(e) {
  if (isWideScreen && window.scrollY > hideThreshold) {
    navShareLink.style.display = "none";
  } else if (isWideScreen && window.scrollY > 1000) {
    navShareLink.style.display = "block";
  } else {
    navShareLink.style.display = "none";
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 06:36:04