Jquery Changing CSS class of object based on numeric content

前端 未结 3 413
粉色の甜心
粉色の甜心 2021-01-25 14:20

Going to be outputting percentages dynamically 0-100%

Want to add CSS class based on percentage. Red for 0% and Blue for 100% progressively.

Markup would be

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-25 14:33

    If you wanna manage the percentage colors yourself manually, you could do it like this:

    $('span').css('color', function() {
     var percentage = parseInt($(this).text());  
        switch(percentage){
            case 100:
              return "red";
            case 90:
              return "gray";                 
        }
    });
    

    example: http://jsfiddle.net/niklasvh/zqwqe/

    edit: alternatively you could calculate the color value dynamically, so you wouldn't have to define each percentage seperately.

        $('').appendTo($('body')).text(i+"%").css('color', function() {
            var percentage = parseInt($(this).text());  
            var colors = [Math.round(255*(percentage/100)),0,255-Math.round(255*(percentage/100))];
            return "rgb("+colors+")";   
            });
    

    example: http://jsfiddle.net/niklasvh/zqwqe/29/

提交回复
热议问题