jquery 进度条
jQuery 进度条实现方法
使用 jQuery 可以轻松创建动态进度条,以下是几种常见的实现方式:
使用 HTML5 <progress> 元素配合 jQuery
HTML5 提供了原生进度条元素,可以通过 jQuery 控制其值:
<progress id="myProgress" value="0" max="100"></progress>
<button id="updateBtn">更新进度</button>
$('#updateBtn').click(function() {
var currentValue = $('#myProgress').val();
if(currentValue < 100) {
$('#myProgress').val(currentValue + 10);
}
});
使用 DIV 模拟进度条
更灵活的方式是用 DIV 元素创建自定义进度条:
<div class="progress-container">
<div class="progress-bar"></div>
</div>
<button id="startProgress">开始</button>
.progress-container {
width: 100%;
height: 20px;
background: #f0f0f0;
}
.progress-bar {
height: 100%;
width: 0%;
background: #4CAF50;
transition: width 0.3s;
}
$('#startProgress').click(function() {
var width = 0;
var interval = setInterval(function() {
if(width >= 100) {
clearInterval(interval);
} else {
width++;
$('.progress-bar').css('width', width + '%');
}
}, 50);
});
使用 jQuery UI 进度条
jQuery UI 提供了专门的进度条组件:
<div id="progressbar"></div>
<button id="uiProgressBtn">开始</button>
$("#progressbar").progressbar({ value: 0 });
$("#uiProgressBtn").click(function() {
var currentValue = $("#progressbar").progressbar("value");
var interval = setInterval(function() {
currentValue += 1;
$("#progressbar").progressbar("value", currentValue);
if(currentValue >= 100) clearInterval(interval);
}, 50);
});
动画效果增强
为进度条添加平滑动画效果:
$('.progress-bar').animate({
width: '100%'
}, {
duration: 2000,
step: function(now) {
$(this).text(Math.round(now) + '%');
}
});
注意事项
- 进度更新应考虑使用 requestAnimationFrame 而非 setInterval 以获得更流畅的动画
- 对于长时间运行的任务,建议使用 Web Workers 避免界面冻结
- 移动端应用需注意触摸事件的兼容性处理







