根据其宽度更改DIV背景颜色 [英] Change DIV Background Color, Depending on Its Width

查看:94
本文介绍了根据其宽度更改DIV背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jQuery根据CSS属性动态修改< div> 的背景颜色, width 值。



这种用法适用于某种形式的颜色代码表,它表明设备在特定类别中表现如何(或差) (有5个),然后有一个'总体'类别,根据一个小数学计算得出总分(将所有5个加在一起并将答案除以5)。

我尝试了两种方法,一种基于我拥有的小jQuery知识,以及另一个从SO上的答案改编而来。两者都包含在我提供的JSFiddle中,后者已被注释掉。



以下是每种颜色的宽度和范围:




  • 0-24%= red - #a41818

  • 25-49%= orange - #87581c

  • <50> 50%-74%=黄色 - #997815
    <75> 75-90%= yellowgreen - #7ba01c
    <91> 91-100% =绿色 - #3a8d24


谢谢!

解决方案 div>

我建议:

  $('。rating-bar')。css('background-color ',function(){
var percent = parseInt($(this).data('size'),10);
if(percentage> 0&& percent< 25){
return'#a41818'
}
else if(percentage> 24&& percent< 50){
return'#87581c';
}
else if(percent> 49&& percent< 75){
return'#997815';
}
else if(percenta ge> 74&& amp; percent< 90){
return'#7ba01c';
}
else if(百分比> 89&& percent< = 100){
return'#3a8d24';
}
});

JS Fiddle演示


I'm wanting to use jQuery to dynamically modify the background color of a <div>, based on its CSS property, width value.

The usage is for some form of color-coded meter, which indicates how well (or poorly) a device performs in a specific category (there are 5), and then there is one 'overall' category, which produces the overall score, based on a little math (add all 5 together and divide the answer by 5).

I have tried two methods, one based on the little jQuery knowledge I have, and the other adapted from an answer on SO. Both are included in the JSFiddle I have provided, with the latter commented out.

Here are the colors and the ranges of the widths for each:

  • 0-24% = red - #a41818
  • 25-49% = orange - #87581c
  • 50-74% = yellow - #997815
  • 75-90% = yellowgreen - #7ba01c
  • 91-100% = green - #3a8d24

Thanks!

解决方案

I'd suggest:

$('.rating-bar').css('background-color', function(){
    var percentage = parseInt($(this).data('size'), 10);
    if (percentage > 0 && percentage < 25){
        return '#a41818'
    }
    else if (percentage > 24 && percentage < 50) {
        return '#87581c';
    }
    else if (percentage > 49 && percentage < 75) {
        return '#997815';
    }
    else if (percentage > 74 && percentage < 90) {
        return '#7ba01c';
    }
    else if (percentage > 89 && percentage <= 100) {
        return '#3a8d24';
    }    
});

JS Fiddle demo.

这篇关于根据其宽度更改DIV背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆