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

滚动200px显示的固定侧边块如何在进入页脚时自动隐藏?

方案1:基于底部距离倒推的判断逻辑

你需要的从页面底部倒推像素的判断逻辑可以直接实现,核心计算逻辑为:文档总高度 - (当前滚动距离 + 视口高度) = 当前视口底部距离页面最底部的距离。

之前直接使用scrollHeight出现异常,大概率是因为页面图片、异步渲染内容等资源未加载完成时就计算了高度,添加资源加载完成的监听即可解决。修改后的完整代码如下:

const navShareLink = document.getElementById('navShareLink');
// 抽离显示/隐藏判断逻辑
function toggleSidebar() {
  const scrollY = window.scrollY;
  const viewportWidth = window.innerWidth;
  const viewportHeight = window.innerHeight;
  const docTotalHeight = document.documentElement.scrollHeight;
  // 计算当前视口底部距离页面最底部的距离
  const distanceToBottom = docTotalHeight - (scrollY + viewportHeight);
  
  // 显示条件:滚动超过200px + 视口宽度大于576px + 距离底部≥300px
  if(scrollY > 200 && viewportWidth > 576 && distanceToBottom >= 300) {
    // 如需保留CSS中设置的opacity过渡效果,可替换为以下两行代码替代display修改
    // navShareLink.style.opacity = "1";
    // navShareLink.style.pointerEvents = "auto";
    navShareLink.style.display = "block";
  } else {
    // navShareLink.style.opacity = "0";
    // navShareLink.style.pointerEvents = "none";
    navShareLink.style.display = "none";
  }
}

// 多事件监听保证状态准确
document.addEventListener('scroll', toggleSidebar);
window.addEventListener('resize', toggleSidebar);
window.addEventListener('load', toggleSidebar); // 所有资源加载完成后重新计算
document.addEventListener('DOMContentLoaded', toggleSidebar); // DOM渲染完成后执行初始判断

方案2:基于Intersection Observer的高性能实现

如果希望逻辑更稳定、滚动性能更好,推荐使用Intersection Observer接口直接监听页脚元素的可见性,不需要手动计算任何高度,自动适配所有页面高度场景:

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

// 基础显示条件判断
function checkBaseCondition() {
  return window.scrollY > 200 && window.innerWidth > 576;
}

// 创建页脚观察者
const footerObserver = new IntersectionObserver((entries) => {
  const isFooterInViewport = entries[0].isIntersecting;
  // 页脚未进入触发区域、且基础条件满足时显示侧边块,否则隐藏
  if(!isFooterInViewport && checkBaseCondition()) {
    navShareLink.style.display = "block";
  } else {
    navShareLink.style.display = "none";
  }
}, {
  // 触发阈值:页脚进入视口300px时触发判断,对应距离底部300px的需求
  rootMargin: '0px 0px -300px 0px'
});

// 启动监听
footerObserver.observe(footer);
// 监听窗口大小和滚动,适配状态变化
document.addEventListener('scroll', () => footerObserver.observe(footer));
window.addEventListener('resize', () => footerObserver.observe(footer));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:45:03