Html 使用css根据数值为文本着色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31803300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:53:28  来源:igfitidea点击:

Coloring the text depending on numeric value using css

htmlcss

提问by anandharshan

I want to color text based on its value, using css.

我想使用 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.

我不想根据值在模板中添加任何类。

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.

我找到了这个链接:如何使用 JavaScript 更改背景颜色?但这还不够,因为我有太多要应用颜色的值。此外,我希望在将来添加新值时它更易于维护。

回答by Giacomo Paita

It is not possibleonly with CSS.

仅使用 CSS是不可能的

You have to use JavaScript/jQuery to dinamically add the color, based on a objectcolor match, and test if the value in the data-colorHTML attribute, is between the range for each element.

您必须使用 JavaScript/jQuery 根据object颜色匹配动态添加颜色,并测试data-colorHTML 属性中的值是否在每个元素的范围之间。

The JS code dynamically check if the element attribute is in a color range and apply the matched color.

JS 代码动态检查元素属性是否在颜色范围内并应用匹配的颜色。

If you will have to add some color and range in the future, simply add new valuesin the colorMatchhash, and update your CSS color class list.

如果您将来必须添加一些颜色和范围,只需在散列中添加新值colorMatch,并更新您的 CSS 颜色类列表。

CSS

CSS

.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'
 };

Here is the working fiddle

这是工作小提琴

回答by Megha Nagpal

A simple approach could be HTML

一个简单的方法可能是 HTML

<div class="content">
    <p>high</p>
</div>
<div class="content">
    <p>low</p>
</div>
<div class="content">
    <p>medium</p>
</div>
<div class="content">
    <p>critical</p>
</div>
<div class="content">
    <p>high</p>
</div>

Jquery
var content = $(".content p").text();

    if (content == "high") {

        $(this).css("color", "#ffffff");
    }
   if (content == "low") {

        $(this).css("color", "#ccc");
    }
   if (content == "critical") {

        $(this).css("color", "#000");
    }