我在进度条上使用 jquery 动画时遇到一些问题。我从数据库中检索一些百分比并将其作为文本放入进度条 div 中,但我找不到更改动画属性中的基本宽度的方法。是否可以根据进度条的当前值更改进度的颜色(即:< 33% -> 红色,< 66% -> 黄色,否则绿色)?
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>
参见demo on JSFiddle .
最佳答案
上下文有错误。选项中的 this
指的是窗口对象,而不是 $(".progress-bar")
$( ".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');
}
}
});
<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>
这是你的工作example
关于javascript - 动画 Bootstrap 进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40265770/