js实现进度条
使用HTML和CSS创建基础结构
进度条需要一个容器和一个表示进度的子元素。HTML结构可以这样设计:
<div class="progress-container">
<div class="progress-bar" id="myProgressBar"></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控制进度
使用DOM操作更新进度条宽度:
function updateProgress(percent) {
const progressBar = document.getElementById('myProgressBar');
progressBar.style.width = percent + '%';
}
// 示例:设置进度为50%
updateProgress(50);
实现动画效果
使用requestAnimationFrame实现平滑动画:
function animateProgress(targetPercent, duration = 1000) {
const progressBar = document.getElementById('myProgressBar');
const startPercent = parseFloat(progressBar.style.width) || 0;
const startTime = performance.now();
function update(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const currentPercent = startPercent + (targetPercent - startPercent) * progress;
progressBar.style.width = currentPercent + '%';
if (progress < 1) {
requestAnimationFrame(update);
}
}
requestAnimationFrame(update);
}
// 示例:动画过渡到75%
animateProgress(75);
监听任务进度
结合实际任务更新进度:
function simulateTask() {
let progress = 0;
const interval = setInterval(() => {
progress += Math.random() * 10;
if (progress >= 100) {
progress = 100;
clearInterval(interval);
}
updateProgress(progress);
}, 300);
}
// 启动模拟任务
simulateTask();
使用HTML5 progress元素
原生progress元素更简单:
<progress id="html5Progress" value="0" max="100"></progress>
<script>
const progressElement = document.getElementById('html5Progress');
progressElement.value = 30; // 设置当前进度
</script>
圆形进度条实现
通过SVG创建圆形进度条:
<svg class="circular-progress" viewBox="0 0 36 36">
<path class="circle-bg"
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="circle-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 setCircleProgress(percent) {
const circle = document.querySelector('.circle-fill');
const circumference = 2 * Math.PI * 15.9155;
const offset = circumference - (percent / 100) * circumference;
circle.style.strokeDasharray = `${circumference} ${circumference}`;
circle.style.strokeDashoffset = offset;
}






