js 实现进度条
使用 HTML 和 CSS 创建基础结构
进度条需要一个容器和一个填充元素。HTML 结构可以简单如下:
<div class="progress-container">
<div class="progress-bar" id="progressBar"></div>
</div>
CSS 样式控制外观:
.progress-container {
width: 100%;
height: 20px;
background-color: #f0f0f0;
border-radius: 10px;
overflow: hidden;
}
.progress-bar {
height: 100%;
width: 0%;
background-color: #4CAF50;
transition: width 0.3s ease;
}
通过 JavaScript 更新进度
使用 style.width 属性动态更新进度条宽度:
function updateProgress(percent) {
const progressBar = document.getElementById('progressBar');
progressBar.style.width = percent + '%';
}
// 示例:更新到50%
updateProgress(50);
实现动画效果
结合 requestAnimationFrame 实现平滑动画:

function animateProgress(targetPercent, duration = 1000) {
const progressBar = document.getElementById('progressBar');
const startWidth = parseFloat(progressBar.style.width) || 0;
const startTime = performance.now();
function step(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const currentPercent = startWidth + (targetPercent - startWidth) * progress;
progressBar.style.width = currentPercent + '%';
if (progress < 1) {
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
}
// 示例:动画过渡到75%
animateProgress(75);
监听实际任务进度
对于真实任务(如文件上传),可以结合事件监听:
// 模拟上传进度事件
const uploadTask = {
start: function() {
let progress = 0;
const interval = setInterval(() => {
progress += 5;
updateProgress(progress);
if (progress >= 100) {
clearInterval(interval);
}
}, 200);
}
};
// 触发上传
document.querySelector('button').addEventListener('click', () => uploadTask.start());
添加文本百分比显示
在进度条内显示当前进度:

<div class="progress-bar" id="progressBar">
<span class="progress-text">0%</span>
</div>
更新 JavaScript:
function updateProgress(percent) {
const progressBar = document.getElementById('progressBar');
progressBar.style.width = percent + '%';
progressBar.querySelector('.progress-text').textContent = Math.round(percent) + '%';
}
响应式设计考虑
通过 CSS 变量实现可定制化:
.progress-container {
--progress-color: #4CAF50;
--progress-height: 10px;
}
.progress-bar {
background-color: var(--progress-color);
height: var(--progress-height);
}
浏览器兼容性处理
对于旧版浏览器,添加前缀或降级方案:
function updateProgress(percent) {
const progressBar = document.getElementById('progressBar');
progressBar.style.width = percent + '%';
progressBar.style.webkitTransition = 'width 0.3s ease'; // 针对Webkit内核
}




