JQuery 'animate' 函数不能流畅地动画化 Bootstrap 进度条的宽度

JQuery 'animate' function doesn't smoothly animate width of Bootstrap progress bar

我正在用 jQuery / Bootstrap 设计动画进度条。我的进度条有8个'steps',每个占整个进度条宽度的12.5%

我设计了一个函数,当动画栏从第一步到第四步变化时效果很好。然而,当出现第五步时,出于某种原因,条形图会在回到 50% 之前动画到 100%。同样的事情发生在第 6、7 和 8 步。

我是不是做错了什么?为什么我的 animate() 函数在第 5 步将条形宽度跳到 100%,然后再调回 62.5%?

javascript

window.total = 0;
window.target = 8;
var progress_percent_full = window.total / window.target;

function update_progress_bar() {
  progress_percent_full = (window.total / window.target) * 100;
  new_width = progress_percent_full + "%";

  $("#progress-bar").animate({
    width: new_width,
  });
  $("#progress-bar").text(total);
}

$("#button").click(function() {
  window.total = window.total + 1;
  update_progress_bar();
});

html

<button class="btn btn-lg btn-primary" id="button">
  Change bar
</button>

<div style="position: fixed; bottom: 0px; left: 0px; right: 0px; height: 75px; background: #dedede;">
        <div class="progress" style="max-width: 500px; margin: 0 auto; position: relative; top: 30px;">
            <div class="progress-bar" id="progress-bar" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="8"></div>
        </div>
    </div>

JSFiddle example 显示正在发生的事情(点击按钮 5-6 次)

显然 .animate() 方法在与百分比一起使用时并不那么可靠。作为替代方案,您可以像这样使用像素值:

function update_progress_bar() {
    var progress = (window.total / window.target),
        new_width = $("#progress-bar").parent().width() * progress;

    $("#progress-bar").animate({
        width: new_width,
    }).text(window.total);
}

或者,您可以删除 .animate() 方法,并使用 css 处理动画。你可以这样做:

<style>
.progress-bar {
    transition: width 1s;
}
<style>

function update_progress_bar() {
    progress_percent_full = (window.total / window.target) * 100;
    var new_width = progress_percent_full + "%";

    $("#progress-bar").width(new_width).text(total);
}