该setTimeout
方法(根据其他答案)是动画基于时间的进度的最常见方法。
But I've had a problem with setTimeout
if the speed is fast or when I want to reset the bar from 100% to 0%, as the default Bootstrap css transitions lead to undesirable animation effects (i.e takes 0.6 seconds to return to 0%). So I suggest tweaking the transition styling to match the desired animation effect e.g
pb = $('[role="progressbar"]')
// immediate reset to 0 without animation
pb.css('transition', 'none');
pb.css('width', '0%');
// now animate to 100% with setTimeout and smoothing transitions
pb.css('transition', 'width 0.3s ease 0s');
var counter = 0;
var update_progress = function() {
setTimeout(function() {
pb.attr('aria-valuenow', counter);
pb.css('width', counter + '%');
pb.text(counter + '%');
if(counter<100) {
counter++;
update_progress();
}
}, 5 * 1000 / 100); // 5 seconds for 100 steps
};
update_progress();
But if you're in the jQuery camp, then jQuery.animate is I think a neater approach as you can forget having to mess with css transition styling and counting steps etc e.g.
pb = $('[role="progressbar"]')
pb.css('transition', 'none'); // if not already done in your css
pb.animate({
width: "100%"
}, {
duration: 5 * 1000, // 5 seconds
easing: 'linear',
step: function( now, fx ) {
var current_percent = Math.round(now);
pb.attr('aria-valuenow', current_percent);
pb.text(current_percent+ '%');
},
complete: function() {
// do something when the animation is complete if you want
}
});
I've put a demo and more discussion on GitHub here.