このsetTimeoutアプローチ(他の回答による)は、時間ベースの進行状況をアニメーション化するための最も一般的なアプローチです。
しかしsetTimeout、速度が速い場合や、バーを 100% から 0% にリセットしたい場合に問題がありました。これは、デフォルトの Bootstrap css トランジションが望ましくないアニメーション効果につながるためです (つまり、0% に戻るのに 0.6 秒かかります)。 . したがって、トランジションのスタイルを微調整して、目的のアニメーション効果に一致させることをお勧めします。
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();
しかし、あなたがjQueryキャンプにいるなら、jQuery.animateは、cssトランジションのスタイリングやステップのカウントなどをいじる必要を忘れることができるので、よりきちんとしたアプローチだと思います.
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
}
});
デモとその他のディスカッションを GitHub here に掲載しました。