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

如何实现滚动至网页container区域后启动progress bar计数

实现滚动到Container区域后启动环形进度条计数

调整CSS使页面可滚动

原代码中body设置为100vh导致页面无法滚动,需修改让页面具备滚动空间,方便测试滚动触发效果:

body{
    height: 200vh; /* 改为200vh让页面可滚动 */
    display: flex;
    align-items: center;
    justify-content: center;
    background: #7d2ae8;
    padding-top: 100vh; /* 可选:将container推至页面下方,便于滚动测试 */
}

修改JavaScript实现滚动触发逻辑

核心思路:监听页面滚动事件,判断container是否进入视口,仅在首次进入时启动进度条动画,避免重复触发。

修改后的完整JavaScript代码:

let circularProgress = document.querySelector(".circular-progress"),
    progressValue = document.querySelector(".progress-value");

let progressStartValue = 0,    
    progressEndValue = 90,    
    speed = 100;
let animationStarted = false; // 标记动画是否已启动

// 封装进度条动画执行逻辑
function startProgressAnimation() {
    let progress = setInterval(() => {
        progressStartValue++;

        progressValue.textContent = `${progressStartValue}%`;
        circularProgress.style.background = `conic-gradient(#7d2ae8 ${progressStartValue * 3.6}deg, #ededed 0deg)`;

        if(progressStartValue === progressEndValue){
            clearInterval(progress);
        }    
    }, speed);
}

// 判断元素是否进入视口的工具函数
function isElementInViewport(el) {
    const rect = el.getBoundingClientRect();
    return (
        rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.bottom >= 0
    );
}

// 监听滚动事件,触发动画
window.addEventListener('scroll', () => {
    if (!animationStarted && isElementInViewport(document.querySelector('.container'))) {
        animationStarted = true;
        startProgressAnimation();
    }
});

// 页面加载时检查:若container初始就在视口内,直接启动动画
window.addEventListener('load', () => {
    if (isElementInViewport(document.querySelector('.container'))) {
        animationStarted = true;
        startProgressAnimation();
    }
});

关键逻辑说明

  • animationStarted变量:确保进度条动画仅执行一次,避免用户来回滚动时重复触发
  • isElementInViewport函数:通过getBoundingClientRect()获取元素的视口位置,判断元素是否处于可见范围内
  • 双监听事件:同时监听页面加载和滚动事件,覆盖所有触发场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 18:40:38