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

页面滚动时步骤动画从0开始及内容显示的JavaScript问题

滚动动画与内容显示解决方案

问题1:滚动到步骤区域时动画从0开始

要让动画在步骤区域滚到顶部后才从0开始推进,核心是精准判断容器进入固定状态的时机,并基于此时的滚动位置计算进度增量:

  • 监听滚动事件,通过getBoundingClientRect().top判断步骤容器是否到达视口顶部
  • 记录容器固定时的滚动位置fixedScrollTop,后续用当前滚动距离减去这个值得到进度增量,确保进度从0开始
  • 给容器添加position: fixed固定在顶部,让动画过程中容器保持可见

问题2:完成步骤后显示隐藏的section

通过进度值判断是否完成所有步骤,触发隐藏内容的显示,同时恢复页面正常滚动:

  • 给隐藏section设置默认display: none,完成步骤后添加类名切换为display: block
  • 进度达到100%时,移除容器的固定定位,让页面可以继续滚动到下方内容

完整代码示例

HTML

<!-- 步骤区域 -->
<div class="steps-container">
  <div class="progress-line"></div>
  <div class="step step-1">步骤1</div>
  <div class="step step-2">步骤2</div>
  <div class="step step-3">步骤3</div>
</div>

<!-- 隐藏的内容区域 -->
<div class="hidden-sections">
  <section>内容区块1</section>
  <section>内容区块2</section>
  <section>内容区块3</section>
</div>

CSS

.steps-container {
  width: 100%;
  height: 300px;
  position: relative;
  background: #f5f5f5;
}
/* 固定在顶部的样式 */
.steps-container.fixed {
  position: fixed;
  top: 0;
  left: 0;
  height: 100vh;
}
.progress-line {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 0;
  height: 4px;
  background: #ffd700;
  transition: width 0.1s linear;
}
.step {
  position: absolute;
  left: 20px;
  height: 60px;
  line-height: 60px;
}
.step-1 { top: 50px; }
.step-2 { top: 120px; }
.step-3 { top: 190px; }
.hidden-sections {
  display: none;
  margin-top: 300px;
  padding: 20px;
}
.hidden-sections.show {
  display: block;
}

JavaScript

const stepsContainer = document.querySelector('.steps-container');
const progressLine = document.querySelector('.progress-line');
const hiddenSections = document.querySelector('.hidden-sections');
let isFixed = false;
let fixedScrollTop = 0;
// 完成三个步骤需要的总滚动距离,根据实际需求调整
const totalScrollNeeded = 600;

window.addEventListener('scroll', () => {
  const rect = stepsContainer.getBoundingClientRect();

  // 触发容器固定并初始化动画起始点
  if (rect.top <= 0 && !isFixed) {
    isFixed = true;
    fixedScrollTop = window.scrollY;
    stepsContainer.classList.add('fixed');
  }

  // 计算进度并更新进度条
  if (isFixed) {
    const scrollDelta = window.scrollY - fixedScrollTop;
    // 限制进度在0-1之间
    const progress = Math.min(scrollDelta / totalScrollNeeded, 1);
    progressLine.style.width = `${progress * 90}%`;

    // 完成所有步骤后显示隐藏内容
    if (progress >= 1) {
      hiddenSections.classList.add('show');
      stepsContainer.classList.remove('fixed');
      // 平滑滚动到内容区域,优化体验
      window.scrollTo({
        top: fixedScrollTop + totalScrollNeeded + stepsContainer.offsetHeight,
        behavior: 'smooth'
      });
      isFixed = false;
    }
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 10:05:12