在权重上添加/删除css类

时间:2014-07-06 15:00:27

标签: javascript jquery html css

我有一个div容器8 child div elements,表示一些颜色条。每个div块包含weight-age 12.5%

<div class="progress-stacked" id="progress-div">
    <div class="progress-bar progress-bar-fail" style="width: 10%; margin-right: 11px;"></div>
    <div class="progress-bar progress-bar-fail" style="width: 10%; margin-right: 11px;"></div>
    <div class="progress-bar progress-bar-fail" style="width: 10%; margin-right: 11px;"></div>
    <div class="progress-bar progress-bar-fail" style="width: 10%; margin-right: 11px;"></div>
    <div class="progress-bar progress-bar-fail" style="width: 10%; margin-right: 12px;"></div>
    <div class="progress-bar progress-bar-fail" style="width: 10%; margin-right: 12px;"></div>
    <div class="progress-bar progress-bar-fail" style="width: 10%; margin-right: 12px;"></div>
    <div class="progress-bar progress-bar-fail" style="width: 10%;"></div>
</div>

我如何用progress-bar-fail替换类progress-bar-success以获取从API获得的值。例如,如果我得到12.5,我希望第一个孩子拥有progress-bar-success而不是progress-bar-fail

如果是25,则应将两个子div替换为progress-bar-success而不是progrss-bar-fail

3 个答案:

答案 0 :(得分:1)

你可以这样做,

var value = 12.5;/*somevalue from your API*/
var targetindex = value/12.5;
targetindex = Math.floor(targetindex);
$(".progress-bar").each(function(i){
    if(i<targetindex)
        $(this).removeClass("progress-bar-fail").addClass("progress-bar-success");
});

看看这里:http://jsfiddle.net/77Kvk/3/

答案 1 :(得分:1)

查看有关工作测试功能的小提琴:http://jsfiddle.net/NEWrq/5/

我根据存在的百分比条数,放弃了硬编码的体重年龄,转而让它自己计算。

var testProgressUpdate = function(per)
{
    var totalBars = $(".progress-bar").length;
    var barsToModify = totalBars * (per / 100);
    barsToModify = Math.round(barsToModify);
    $(".progress-bar").removeClass().addClass("progress-bar").addClass("progress-bar-fail");
    $(".progress-bar").each(function(i)
    {
        if (i >= barsToModify) return false;        
        $(this).removeClass("progress-bar-fail").addClass("progress-bar-success");
    });
}
testProgressUpdate(50); // 4 bars
//testProgressUpdate(12.5); // 1 bar
//testProgressUpdate(13.5); // 1 bar
//testProgressUpdate(24); // 2 bars

答案 2 :(得分:1)

这是我的尝试

function progressUpdate(value) {
  var n = Math.floor(value / 12.5);
  $(".progress-bar:lt(" + n + ")").removeClass("progress-bar-fail").addClass("progress-bar-success");
  $(".progress-bar:gt(" + (n-1) + ")").removeClass("progress-bar-success").addClass("progress-bar-fail");
}

Demo