I want to animate a progress bar's width from 0% to 70% over 2.5 seconds. However, the code below immediately changes the width to 70% after a 2.5 second delay. What am I missing?

$(".progress-bar").animate({
    width: "70%"
}, 2500);

JSFiddle: http://jsfiddle.net/WEYKL/

有帮助吗?

解决方案

The problem is in default Bootstrap transition effect, which animates any update of the width property.

If you switch it off with supressing the corresponding style, it will work fine, e.g.:

.progress-bar {
    -webkit-transition: none !important;
    transition: none !important;
}

DEMO: http://jsfiddle.net/WEYKL/1/

其他提示

So, it makes more sense to adjust the transition effect via CSS or jQuery.

.progress-bar {
    -webkit-transition: width 2.5s ease;
    transition: width 2.5s ease;
}

And just change the width value.

$(".progress-bar").css('width', '70%');

IT'S very EASY if uses bootstrap progress bar,

only add attrib aria-valuenow="percent_required%" to div with class "progress-bar" like this:

<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="57%" aria-valuemin="0" aria-valuemax="57">

Next, on script:

<script>
  $(document).on('ready',function(){
    $('.progress .progress-bar').css("width",function() {
      return $(this).attr("aria-valuenow") + "%";
    })
  })
</script>

Reload, Go!

You can fix it by adding:

.progress .progress-bar {
  transition: unset;
}

var delay = 500;
$(".progress-bar").each(function(i) {
  $(this).delay(delay * i).animate({
    width: $(this).attr('aria-valuenow') + '%'
  }, delay);

  $(this).prop('Counter', 0).animate({
    Counter: $(this).text()
  }, {
    duration: delay,
    // easing: 'swing',
    step: function(now) {
      $(this).text(Math.ceil(now) + '%');
    }
  });
});
.progress {
  margin-bottom: 20px;
}

.progress-bar {
  width: 0;
}

.bg-purple {
  background-color: #825CD6 !important;
}

.progress .progress-bar {
  transition: unset;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

<div class="container">
  <h2>Bootstrap 4 Progress Bars</h2>
  <div class="progress border">
    <div class="progress-bar progress-bar-striped progress-bar-animated bg-danger" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100">70</div>
  </div>
  <div class="progress border">
    <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100">50</div>
  </div>
  <div class="progress border">
    <div class="progress-bar progress-bar-striped progress-bar-animated bg-purple" role="progressbar" aria-valuenow="90" aria-valuemin="0" aria-valuemax="100">90</div>
  </div>
</div>

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top