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

jQuery实现的技能进度条动画运行时百分比计数功能失效求助

问题修复方案

核心问题原因

  • 滚动事件未加执行锁,只要进度条区域在可视范围内,每次滚动都会重复触发动画,导致百分比计数混乱
  • CSS过渡动画和jQuery animate动画逻辑分离,容易出现进度条宽度和数值更新不同步的问题
  • 读取percent属性时未转换为数字类型,部分场景下会出现数值计算异常
  • 未初始化percent属性值,首次加载时百分比位置可能显示空值

修改后的代码

JS代码

jQuery(function($){
  // 初始化进度条状态
  $('.project-percent').attr('percent', '0%').data('animated', false);

  $(window).scroll(function() {
    var top_of_element = $(".work-process").offset().top;
    var bottom_of_element = $(".work-process").offset().top + $(".work-process").outerHeight();
    var bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
    var top_of_screen = $(window).scrollTop();

    if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
      $('.project-percent').each(function(){
        var $this = $(this);
        // 已执行过动画的进度条跳过处理
        if ($this.data('animated')) return;
        // 转换为数值类型避免计算错误
        var percent = parseInt($this.attr('percent'));
        
        $({animatedValue: 0}).animate({animatedValue: percent},{
          duration: 2000,
          step: function(){
            var currentVal = Math.floor(this.animatedValue);
            $this.attr('percent', currentVal + '%');
            // 同步更新进度条宽度,保证和数值完全对齐
            $this.css('width', currentVal + '%');
          },
          complete: function(){
            var currentVal = Math.floor(this.animatedValue);
            $this.attr('percent', currentVal + '%');
            $this.css('width', currentVal + '%');
            // 标记动画已完成,避免重复触发
            $this.data('animated', true);
          }
        });
      });
    }
  });
});

CSS代码

仅需删除.project-percent选择器中的transition: 2s linear;属性即可,其余样式保持不变:

.nb-progressbar-row {width: 90%;margin: 0 auto;}
.project{width: 60%;margin: 0 auto;}
.work-process h3 {margin: 30px 0px 10px;}
.project-bar {height: 18px;background: #e0e0e0;border-radius: 30px;}
.project-percent {
  height: 18px;
  background-color: #2196F3;
  border-radius: 30px;
  position: relative;
  width: 0;
}
.project-percent::before {
  content: attr(percent);
  position: absolute;
  right: 0px;
  left: 0px;
  padding: 1px 0px;
  color: #ffffff;
  font-size: 15px;
  border-radius: 25px;
  font-weight: bold;
  width: 20px;
  margin: 0px auto;
}

HTML代码无需修改,修改完成后滚动到进度条区域时,百分比数值会和进度条宽度同步从0增长到目标值,且只会触发一次动画,不会出现重复跳动的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:24:02