【问题标题】:Coloring the text depending on numeric value using css使用css根据数值为文本着色
【发布时间】:2015-10-26 12:07:18
【问题描述】:

我想根据文本的值使用 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.

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

我找到了这个链接:How do I change the background color with JavaScript?,但这还不够,因为我有太多的值要应用颜色。 我还希望它在将来添加新值时更易于维护。

【问题讨论】:

  • 不加类?您可以根据文本颜色的值动态添加类的唯一方法。使用 if...else 或 switch
  • IMPOSSIBLE 只有 CSS
  • 请给我们您的代码示例,以便我们为您提供可行的解决方案(即:在JSFiddle发帖
  • 您不仅想根据元素的内容设置样式(目前还不可能),还想根据内容有条件地设置样式。 CSS 不是为此而构建的。

标签: html css


【解决方案1】:

不可能仅使用 CSS。

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

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

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

##CSS

.red {color:red}

###HTML

<p data-color="19">Lorem 19</p>

###JS

var colorMatch = {
    '0-19'     : 'red',
    '20-59'    : 'orange',
    '60-100'   : 'green'
 };

Here is the working fiddle

【讨论】:

  • 这种方法似乎很容易维护。谢谢。
  • 如果 data-color="19" 是 asp 标签的结果而不是“19”会怎样?
  • 这种情况下,你不能使用我的JS:你必须事先知道asp标签的结果,并根据它编写一个脚本。
【解决方案2】:

一个简单的方法可能是 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");
    }

【讨论】:

  • 您的代码没有回答问题。您正在匹配精确的文本值,但问题在于在某些间隔内匹配 int 值
  • 我喜欢,只需添加 .valueOf() 即可转换为数字并进行数字大小写。
猜你喜欢
  • 2012-05-18
  • 2020-07-10
  • 1970-01-01
  • 2019-04-19
  • 2016-08-27
  • 2020-06-10
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
相关资源
最近更新 更多