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控制进度
使用JavaScript动态更新进度条宽度:
function updateProgress(percentage) {
const progressBar = document.getElementById('progressBar');
progressBar.style.width = percentage + '%';
}
// 示例:设置进度为50%
updateProgress(50);
实现动画效果
为进度变化添加平滑动画:
function animateProgress(targetPercentage, duration = 1000) {
const progressBar = document.getElementById('progressBar');
const startPercentage = parseFloat(progressBar.style.width) || 0;
const startTime = performance.now();
function update(timestamp) {
const elapsed = timestamp - startTime;
const progress = Math.min(elapsed / duration, 1);
const currentPercentage = startPercentage + (targetPercentage - startPercentage) * progress;
progressBar.style.width = currentPercentage + '%';
if (progress < 1) {
requestAnimationFrame(update);
}
}
requestAnimationFrame(update);
}
// 示例:从当前进度动画到75%
animateProgress(75);
响应式进度条
创建响应不同状态的进度条样式:
.progress-bar.warning {
background-color: #ff9800;
}
.progress-bar.error {
background-color: #f44336;
}
.progress-bar.complete {
background-color: #2196F3;
}
JavaScript中添加状态判断:
function setProgress(percentage) {
const progressBar = document.getElementById('progressBar');
progressBar.style.width = percentage + '%';
progressBar.classList.remove('warning', 'error', 'complete');
if (percentage < 30) {
progressBar.classList.add('error');
} else if (percentage < 70) {
progressBar.classList.add('warning');
} else {
progressBar.classList.add('complete');
}
}
圆形进度条实现
HTML结构:
<div class="circular-progress">
<svg 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>
<div class="percentage-text">0%</div>
</div>
CSS样式:
.circular-progress {
position: relative;
width: 100px;
height: 100px;
}
.circle-bg {
fill: none;
stroke: #eee;
stroke-width: 3;
}
.circle-fill {
fill: none;
stroke: #4CAF50;
stroke-width: 3;
stroke-linecap: round;
transition: stroke-dasharray 0.5s ease;
}
.percentage-text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 16px;
}
JavaScript控制:

function updateCircularProgress(percent) {
const circle = document.querySelector('.circle-fill');
const text = document.querySelector('.percentage-text');
const circumference = 2 * Math.PI * 15.9155;
const dashValue = (percent / 100) * circumference;
circle.style.strokeDasharray = `${dashValue}, ${circumference}`;
text.textContent = `${percent}%`;
}






