Animating Bootstrap progress bar width with jQuery

自作多情 提交于 2019-11-30 08:08:49
VisioN

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/

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!

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%');

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!