Animate Bootstrap进度条

时间:2016-10-26 15:02:35

标签: javascript jquery html twitter-bootstrap

我在进度条上使用带有jquery的动画时遇到了一些麻烦。我从数据库中检索一些百分比并将其作为文本放在进度条div中,但我找不到一种方法来更改动画属性中的基本宽度。是否可以根据进度条的当前值更改进度的颜色(即:< 33% - > red,< 66% - > yellow,否则为绿色)?



console.log($(".progress-bar").text())

$(".progress-bar").animate({
  width: $(this).text() //I want to get the value inside the progressbar div but doesn't seems like to work
}, {
  duration: 2000,
  step: function(now, fx) {}
});

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="col-xs-12 col-sm-12 progress-container">
  <div class="progress progress-striped active">
    <!-- Part retrieved from the database -->
    <div class="progress-bar progress-bar-success" style="width:0%">60%</div>
  </div>
</div>
&#13;
&#13;
&#13;

请参阅demo on JSFiddle

1 个答案:

答案 0 :(得分:3)

上下文存在错误。选项中的this是指窗口对象,而不是$(".progress-bar")

&#13;
&#13;
$( ".progress-bar" ).animate({
   width: $( ".progress-bar" ).text()
}, {
   duration: 2000,
   step: function( now, fx ) {
  	      $(this).removeClass (function (index, css) {
	     return (css.match (/(^|\s)progress-bar-\S+/g) || []).join(' ');
      });
  	      if (now < 33) {
  		     $(this).addClass('progress-bar-danger');
      } else if (now < 66) {
	     $(this).addClass('progress-bar-warning');
      } else {
	     $(this).addClass('progress-bar-success');
      }
   }
});
&#13;
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="col-xs-12 col-sm-12 progress-container">
  <div class="progress progress-striped active">
    <!-- Part retrieved from the database -->
    <div class="progress-bar progress-bar-success" style="width:0%">60%</div>
  </div>
</div>
&#13;
&#13;
&#13;

这是您的工作example