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

如何在滚动到指定DIV底部时隐藏阅读进度条?

解决阅读进度条滚动到DIV底部时隐藏的问题

你的代码存在两个核心问题导致闪烁和逻辑错误:

  1. 进度计算未考虑窗口高度,导致进度值无法准确对应到内容底部的滚动位置
  2. 滚动事件触发频繁,反复执行fadeIn()/fadeOut()引发动画闪烁

修改后的完整代码

HTML

<div class="progress-bar"></div>
<header>HEADER</header>
<main class="content">Content</main>
<footer>FOOTER</footer>

CSS

.progress-bar {
  background-color: #f00;
  position: fixed;
  left: 0;
  top: 0;
  height: 5px;
  width: 0;
  transition: width .3s ease;
  z-index: 999;
  display: none; /* 默认隐藏进度条 */
}

jQuery

$(window).scroll(function() {
  var $content = $('.content');
  var contentTop = $content.offset().top;
  var contentHeight = $content.height();
  var windowHeight = $(window).height();
  // 计算内容的实际可滚动高度(内容总高度减去窗口可视高度)
  var scrollableHeight = contentHeight - windowHeight;
  // 计算当前滚动位置相对于内容区域的偏移量
  var scrollOffset = $(window).scrollTop() - contentTop;
  
  var $progressBar = $('.progress-bar');
  // 进入内容区域且未滚动到底部时,显示并更新进度条
  if (scrollOffset >= 0 && scrollOffset < scrollableHeight) {
    if (!$progressBar.is(':visible')) {
      $progressBar.fadeIn();
    }
    var progress = (scrollOffset / scrollableHeight) * 100;
    $progressBar.css('width', progress + '%');
  } else {
    // 离开内容区域或滚动到底部时,隐藏进度条并重置宽度
    if ($progressBar.is(':visible')) {
      $progressBar.fadeOut();
    }
    $progressBar.css('width', '0%');
  }
});

关键改进点

  • 修正进度计算逻辑:用内容高度 - 窗口高度作为可滚动总高度,确保滚动到内容底部时进度刚好达到100%,触发隐藏逻辑
  • 添加状态判断:通过:visible检查进度条当前状态,避免在滚动事件中反复触发动画,彻底解决闪烁问题
  • 默认隐藏处理:CSS中设置display: none,避免页面加载时进度条短暂显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 02:42:23