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

滚动控制元素显隐:页面接近底部时元素消失的JS实现问题

解决滚动到页面底部时隐藏固定元素的问题

原代码实现了滚动超过指定距离后显示右侧固定元素,现在需要补充功能:当滚动接近页面底部时自动隐藏元素,离开底部区域后恢复显示。以下是修正后的完整代码及关键说明:

完整代码

JavaScript

jQuery(document).on('scroll', () => {
  const $element = jQuery('.ast-below-header-bar');
  const scrollTop = $(window).scrollTop();
  // 顶部显示阈值:滚动超过此距离时显示元素
  const topThreshold = 350;
  // 底部隐藏阈值:距离底部小于此值时隐藏元素
  const bottomThreshold = 200;
  // 计算当前滚动位置到页面底部的剩余距离
  const distanceToBottom = $(document).height() - $(window).height() - scrollTop;

  // 同时满足「超过顶部阈值」且「未接近底部」时,显示元素,否则隐藏
  if (scrollTop > topThreshold && distanceToBottom > bottomThreshold) {
    $element.addClass('filterr');
  } else {
    $element.removeClass('filterr');
  }
});

CSS

body {
  height: 500vh
}

.ast-below-header-bar {
  display: grid;
  position: fixed;
  right: -150px;
  top: 14%;
  background: red;
  height: 200px;
  width: 200px;
  transition: .3s;
}

.ast-below-header-bar.filterr {
  right: 7px!important;
}

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ast-below-header-bar"></div>

关键修改说明

  1. 修正底部位置计算逻辑:
    之前直接用scrollTop > scrollBottom的方式错误,正确做法是计算当前滚动位置到页面底部的剩余距离:$(document).height() - $(window).height() - scrollTop,当这个值小于设置的bottomThreshold(比如200px),就判定为接近底部。
  2. 合并判断条件:
    元素显示需要同时满足两个条件:滚动距离超过顶部阈值,且未接近页面底部,只要其中一个不满足就隐藏元素。
  3. 简化scrollTop获取:
    使用$(window).scrollTop()统一获取滚动距离,避免原代码中document.body.scrollTop和document.documentElement.scrollTop的兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:45:34