使用jQuery动画Bootstrap进度条宽度

25

我想将一个进度条从0%到70%地动态地展示出来,时长为2.5秒。但是下面的代码在延迟2.5秒后立即将宽度更改为70%。我错过了什么吗?

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

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


1
朋友,你用什么浏览器进行测试?我在 Firefox 28 中检查了你的代码,一切正常。 - Amit
4个回答

46

问题出在默认的Bootstrap过渡效果上,该效果会使width属性的任何更新都产生动画效果。

如果通过抑制相应的样式来关闭它,它将正常工作,例如:

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

演示: http://jsfiddle.net/WEYKL/1/


1
搞定了。我刚刚注意到Safari可以很好地处理动画,但是Chrome在Bootstrap的过渡效果上有问题。谢谢! - user3088077
1
是的,很可能Chrome尝试将两种动画合并,并在jQuery动画已经在内部完成时仅显示CSS过渡。 - VisioN
如何在同一页中使用多个进度条? - PeterPam
如何使它线性? - Kamel Labiad

7

因此,通过CSS或jQuery调整过渡效果更有意义。

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

只需要更改宽度的值即可。

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

4

如果使用Bootstrap进度条,这很容易实现

只需要在class为“progress-bar”的div中添加属性aria-valuenow="percent_required%"即可,格式如下:

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

接下来,关于脚本:

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

重新加载,出发!


3
您可以通过添加以下内容来修复它:
.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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接