JQuery'animate'函数不能平滑地为Bootstrap进度条的宽度设置动画

问题描述 投票:1回答:1

我正在使用jQuery / Bootstrap设计一个动画进度条。我的进度条有8个“步骤”,每个步骤代表整个进度条宽度的12.5%。

我设计了一个功能,当动画条从第一步到第四步改变时效果很好。但是,当第五步出现时,由于某种原因,该条形图会动画到100%,然后再回到50%。在步骤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次)

jquery jquery-animate progress-bar width bootstrap-4
1个回答
2
投票

显然,当使用百分比时,.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);
}
© www.soinside.com 2019 - 2024. All rights reserved.