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

如何使用jQuery实现进度条仅单次以百分比单位的动画效果?

解决进度条重复触发动画的问题

我来帮你搞定这个重复触发动画的小问题~你遇到的核心问题是每次鼠标悬停都会调用animate()方法,哪怕进度条已经到达目标宽度,导致动画重复执行。这里有两种靠谱的解决方案,推荐优先用纯CSS的方式,更简洁也更适配响应式需求。

方案一:纯CSS实现(推荐)

用CSS的transition和:hover伪类就能完美解决,既避免了JS的重复触发问题,又天然支持响应式:

修改后的CSS代码

#langages{
  height: 100px;
}
#fr {
  width: 20%;
  /* 添加入场过渡动画,可自定义时长和缓动效果 */
  transition: width 0.3s ease-in-out;
}
/* 父元素悬停时,触发进度条宽度变化 */
#langages:hover #fr {
  width: 90%;
}
.size {
  max-height: 25em;
}
.bgBlue{
  background-color: #5DD5FF;
}

对应的HTML(无需JS)

<div id="langages" class="bg-white col-10 text-center mx-auto mb-5 fs-5 shadow rounded size">
  <div class="col-11 mx-auto my-4 text-start">
    Français
    <div class="progress mt-1">
      <div class="progress-bar bgBlue" id="fr" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100">
        <span class="sr-only">90% Complete</span>
      </div>
    </div>
  </div>
</div>

这种方式的优势:

  • 无需JS,性能更优
  • 天然支持响应式,缩放页面时自动适配
  • 只有在悬停状态变化时才触发动画,不会重复执行

方案二:改进jQuery代码

如果你必须用JS实现,可以通过判断当前进度条宽度,避免重复触发动画:

修改后的JS代码

$(document).ready(function () {
  $("#langages").on('mouseenter', function () {
    const $progressBar = $("#fr");
    const parentWidth = $progressBar.parent().width();
    const targetWidth = parentWidth * 0.9;
    
    // 只有当当前宽度未达到目标值时,才执行动画(减1避免浮点精度问题)
    if ($progressBar.width() < targetWidth - 1) {
      $progressBar.stop(true, false).animate({ width: "90%" });
    }
  });
});

这里的stop(true, false)是为了清除之前未完成的动画队列,避免动画堆积;同时通过判断当前宽度是否接近目标值,防止重复触发。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 15:49:04