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

如何实现滚动特定div时顶部progress bar启动,离开该div时停止?

Targeted Progress Bar Implementation

To make the progress bar only activate when scrolling through a specific div, we'll adjust the logic to track the target element's position and calculate progress only within its visible range.

Step 1: Update HTML

Add a unique class to your target div so we can select it easily:

<div class="progress"></div>

<div class="content">Scroll Down</div>
<div class="content target-section">This is the section to track</div>
<div class="content">Even Further</div>
<div class="content">You Made It All The Way!</div>

Step 2: Add Basic CSS for Progress Bar

Style the progress bar to be fixed at the top for visibility:

.progress {
  position: fixed;
  top: 0;
  left: 0;
  height: 4px;
  background-color: #2196F3;
  width: 0%;
  z-index: 1000;
}

.content {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
}

Step 3: Adjust JavaScript Logic

Modify the scroll handler to only calculate progress when scrolling through the target section:

$(document).ready(function() {
  const $progress = $(".progress");
  const $target = $(".target-section");
  
  // Calculate key positions once on page load
  const targetTop = $target.offset().top;
  const targetHeight = $target.outerHeight();
  const windowHeight = $(window).height();
  
  // Start point: when top of target enters the viewport
  const startScroll = targetTop - windowHeight;
  // End point: when bottom of target exits the viewport
  const endScroll = targetTop + targetHeight;

  $(document).on("scroll", function() {
    const scrollPos = $(document).scrollTop();
    
    if (scrollPos < startScroll || scrollPos > endScroll) {
      // Reset progress bar when outside the target range
      $progress.css("width", "0%");
      return;
    }
    
    // Calculate progress percentage within the target's visible range
    const scrollRange = endScroll - startScroll;
    const currentProgress = (scrollPos - startScroll) / scrollRange;
    const progressPercent = currentProgress * 100;
    
    $progress.css("width", progressPercent + "%");
  });
});

Key Behavior

  • Start Trigger: The progress bar begins filling when the top edge of the target div enters the viewport.
  • End Trigger: The progress bar resets to 0 when the bottom edge of the target div exits the viewport.
  • Progress Calculation: The percentage is based on how much of the target's total visible range has been scrolled through.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 08:04:44