h5实现进度条
使用HTML5的<progress>标签
HTML5提供了原生进度条标签<progress>,适用于展示任务完成进度。基本语法如下:
<progress value="50" max="100"></progress>
value:当前进度值(必需)max:总进度值(默认1)
自定义CSS样式
通过CSS可以美化原生进度条:
progress {
width: 300px;
height: 20px;
border-radius: 10px;
}
progress::-webkit-progress-bar {
background-color: #f0f0f0;
}
progress::-webkit-progress-value {
background-color: #4CAF50;
}
动态更新进度
结合JavaScript实现动态进度更新:
let progressBar = document.querySelector('progress');
let currentValue = 0;
setInterval(() => {
currentValue += 10;
if(currentValue > 100) currentValue = 0;
progressBar.value = currentValue;
}, 500);
使用Canvas绘制高级进度条
需要更复杂效果时可用Canvas实现:
<canvas id="myProgress" width="300" height="30"></canvas>
<script>
const canvas = document.getElementById('myProgress');
const ctx = canvas.getContext('2d');
function drawProgress(percent) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 背景
ctx.fillStyle = '#e0e0e0';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 进度
ctx.fillStyle = '#FF7043';
ctx.fillRect(0, 0, canvas.width * percent/100, canvas.height);
// 文字
ctx.fillStyle = '#000';
ctx.font = '14px Arial';
ctx.fillText(`${percent}%`, 10, 20);
}
let p = 0;
setInterval(() => {
p = (p + 5) % 105;
drawProgress(Math.min(p, 100));
}, 200);
</script>
使用第三方库
常见进度条库推荐:
- ProgressBar.js:支持圆形、直线等多种形状
- NProgress:适用于页面顶部细进度条
- anime.js:实现带动画效果的进度条
安装示例(以NProgress为例):
npm install nprogress
使用代码:
import NProgress from 'nprogress';
NProgress.start();
setTimeout(() => NProgress.done(), 2000);


