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

如何用Vanilla JavaScript实现仅针对<main>元素的滚动进度条?

实现仅针对
元素的滚动进度条

你的代码有两个关键问题导致功能失效:

  1. <main>元素默认不会生成自身的滚动条,内容会直接溢出到页面,所以main.scrollTop始终为0
  2. 你监听的是window的滚动事件,而不是<main>元素自己的滚动事件

下面是修复后的完整代码:

修改后的CSS(核心是给
加滚动属性)

.nav {
    background-color: black;
    height:50px;
}
section {
    height: 400px;
}

.scroll {
    width: 100%;
    height: 4px;
    background-color: lightgray;
}

#scroll-progress {
    width: 0%;
    height: 4px;
    background-color: green;
}

/* 新增:让main拥有独立滚动区域 */
main {
    height: 600px; /* 可根据需求调整高度,比如用calc(100vh - 头部总高度)自适应视口 */
    overflow-y: auto; /* 垂直内容溢出时显示滚动条 */
}

修改后的JS(监听main的滚动事件)

const main = document.querySelector('main');
const progressBar = document.getElementById('scroll-progress');

function updateProgress() {
    const scrollTop = main.scrollTop;
    const totalScrollable = main.scrollHeight - main.clientHeight;
    // 防止内容不足时出现计算错误
    const progress = totalScrollable > 0 ? (scrollTop / totalScrollable) * 100 : 0;
    progressBar.style.width = `${progress}%`;
}

// 监听main的滚动事件,而非window
main.addEventListener('scroll', updateProgress);

// 初始化时触发一次,确保进度条初始状态正确
updateProgress();

HTML(保持原结构不变)

<body>
    <header>
        <section>
        </section>
    </header>
    <nav>
        <div class="nav"></div>
        <div class="scroll">
                <div class="scroll-bar" id="scroll-progress"></div>
        </div>
    </nav>
    <main>
        <section>
            <p>some content</p>
        </section>
        <section>
            <p>some content</p>
        </section>
    </main>
    <section>
        <p>some content</p>
    </section>
    <section>
        <p>some content</p>
    </section>
</body>

补充说明

  • 如果想让<main>高度自适应浏览器窗口,可以把height: 600px改成height: calc(100vh - 90px)(90px是header的section高度40px加上nav的.nav高度50px,根据实际布局调整)
  • 加入了totalScrollable > 0的判断,避免当main内容过少、不需要滚动时出现NaN的异常情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 20:07:43