使用CSS根据数值为文本着色 [英] Coloring the text depending on numeric value using css
问题描述
我想使用CSS根据文本的颜色为文本着色。
I want to color text based on its value, using css.
ie. if value is less than 20 --> red ,
if value is between 20 - 60 --> orange ,
if value is greater than 60 to 100--> green.
我不想根据值在模板中添加任何类。
I don't want to add any class in the template depending on the value.
我找到了此链接:如何使用JavaScript更改背景颜色?,但是这并不够,因为我有太多要应用颜色的值。
另外,我希望将来在添加新值时更易于维护。
I found this Link: How do I change the background color with JavaScript? but it doesn't suffice as I have too many values to apply color to. Also I want it to be more maintainable when adding new values in future.
推荐答案
这不是
It is not possible only with CSS.
您必须使用JavaScript / jQuery根据对象$>动态添加颜色。 c $ c>颜色匹配,并测试
data-color
HTML属性中的值是否在每个元素的范围之间。
You have to use JavaScript/jQuery to dinamically add the color, based on a object
color match, and test if the value in the data-color
HTML attribute, is between the range for each element.
JS代码会动态检查element属性是否在颜色范围内,并应用匹配的颜色。
The JS code dynamically check if the element attribute is in a color range and apply the matched color.
如果将来需要添加一些颜色和范围,只需在 colorMatch
哈希值中添加新值,然后更新CSS颜色类列表。
If you will have to add some color and range in the future, simply add new values in the colorMatch
hash, and update your CSS color class list.
.red {color:red}
HTML
HTML
<p data-color="19">Lorem 19</p>
JS
JS
var colorMatch = {
'0-19' : 'red',
'20-59' : 'orange',
'60-100' : 'green'
};
这篇关于使用CSS根据数值为文本着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!