js 进度条的实现
使用 HTML 和 CSS 创建基础进度条
HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度:
<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 + '%';
}
// 示例:更新进度到75%
updateProgress(75);
实现动画效果
结合 requestAnimationFrame 实现平滑动画:
function animateProgress(targetPercent, duration = 1000) {
const progressBar = document.getElementById('progressBar');
const startTime = performance.now();
const startWidth = parseFloat(progressBar.style.width) || 0;
function step(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const currentWidth = startWidth + (targetPercent - startWidth) * progress;
progressBar.style.width = currentWidth + '%';
if (progress < 1) {
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
}
// 示例:动画形式过渡到90%
animateProgress(90);
使用 HTML5 <progress> 元素
原生进度条元素更简洁:
<progress id="nativeProgress" value="0" max="100"></progress>
JavaScript 控制:
const progressElement = document.getElementById('nativeProgress');
progressElement.value = 50; // 设置进度为50%
圆形进度条实现
通过 SVG 或 Canvas 实现圆形进度条:
<svg class="circular-progress" viewBox="0 0 36 36">
<path class="track" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"/>
<path class="fill" stroke-dasharray="0, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"/>
</svg>
JavaScript 控制:
function updateCircleProgress(percent) {
const fill = document.querySelector('.fill');
const circumference = 2 * Math.PI * 15.9155;
const offset = circumference - (percent / 100) * circumference;
fill.style.strokeDasharray = `${circumference} ${circumference}`;
fill.style.strokeDashoffset = offset;
}
updateCircleProgress(75);
进度条事件监听
添加事件监听实现交互:
document.getElementById('progressButton').addEventListener('click', () => {
let currentProgress = 0;
const interval = setInterval(() => {
currentProgress += 5;
updateProgress(currentProgress);
if (currentProgress >= 100) clearInterval(interval);
}, 200);
});






