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

如何用JavaScript实现CSS线性渐变百分比变化的动画效果?

实现进度条百分比变化的平滑动画

方法1:嵌套元素+CSS过渡(最推荐,兼容性好)

这种方法通过两层元素实现,外层作为进度条背景,内层是填充的进度块,利用CSS的transition实现宽度变化的平滑动画,比直接操作渐变更稳定可控。

HTML结构调整

<div id="pointThreshold" class="progress-container">
  <div class="progress-fill"></div>
</div>

CSS样式设置

.progress-container {
  /* 根据需求自定义宽高 */
  width: 300px;
  height: 24px;
  background-color: #1b1f20;
  overflow: hidden;
  /* 可选:添加圆角优化视觉效果 */
  border-radius: 12px;
}

.progress-fill {
  height: 100%;
  background-color: rgb(255, 230, 0);
  width: 0%;
  /* 配置过渡动画:时长0.3s,缓动曲线ease,可自行调整参数 */
  transition: width 0.3s ease;
}

JavaScript更新逻辑

const progressFill = document.querySelector('.progress-fill');

// 传入目标百分比即可更新进度
function updateProgress(targetPercentage) {
  progressFill.style.width = `${targetPercentage}%`;
}

// 调用示例:更新到60%进度
updateProgress(60);

方法2:CSS变量+背景渐变过渡

如果不想修改原有HTML结构,可以用CSS变量配合transition实现渐变百分比的平滑变化,适用于现代浏览器。

CSS样式设置

#pointThreshold {
  /* 基础样式:自定义宽高 */
  width: 300px;
  height: 24px;
  /* 使用CSS变量--progress控制渐变占比 */
  background: linear-gradient(to right, rgb(255, 230, 0) var(--progress, 0%), #1b1f20 0%);
  /* 给background属性添加过渡效果 */
  transition: background 0.3s ease;
  /* 可选圆角 */
  border-radius: 12px;
}

JavaScript更新逻辑

const progressBar = document.getElementById("pointThreshold");

function updateProgress(targetPercentage) {
  // 修改CSS变量的值触发过渡
  progressBar.style.setProperty('--progress', `${targetPercentage}%`);
}

// 调用示例:更新到75%进度
updateProgress(75);

方法3:JavaScript逐帧动画(自定义精细控制)

如果需要更灵活的动画控制(比如自定义缓动曲线、中途暂停/打断),可以用requestAnimationFrame逐帧更新百分比。

JavaScript实现

// 记录当前进度百分比
let currentProgress = 0;
const progressBar = document.getElementById("pointThreshold");

/**
 * 动画更新进度
 * @param {number} targetPercentage - 目标百分比
 * @param {number} duration - 动画时长(毫秒),默认500ms
 */
function animateProgress(targetPercentage, duration = 500) {
  const startProgress = currentProgress;
  const difference = targetPercentage - startProgress;
  const startTime = Date.now();

  function update() {
    const elapsed = Date.now() - startTime;
    // 线性缓动计算当前进度,可替换为其他缓动公式(如ease-in-out)
    currentProgress = startProgress + difference * Math.min(elapsed / duration, 1);
    
    // 更新背景渐变
    progressBar.style.background = `linear-gradient(to right, rgb(255, 230, 0) ${currentProgress}%, #1b1f20 0%)`;

    if (elapsed < duration) {
      requestAnimationFrame(update);
    } else {
      // 确保最终进度精确匹配目标值
      currentProgress = targetPercentage;
      progressBar.style.background = `linear-gradient(to right, rgb(255, 230, 0) ${currentProgress}%, #1b1f20 0%)`;
    }
  }

  requestAnimationFrame(update);
}

// 调用示例:用500ms动画到80%进度
animateProgress(80, 500);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:10:16