【问题标题】:How to color table entries based on value如何根据值为表格条目着色
【发布时间】:2017-06-03 20:10:14
【问题描述】:

我想要做的是将所有内容为“x”的<td>-条目设为红色。

所以在:

<table>
    <tr>
        <td>Mini Contests</td>
        <td>5</td>
        <td>5.0</td>
        <td>x</td>
        <td>x</td>
        <td>x</td>
        <td>x</td>
    </tr>
</table>

最后 4 个条目应该是红色的。

【问题讨论】:

  • 你不能只用 html 和 css 做到这一点
  • 对 td 使用内联 css
  • 在 css 中使用 tr td:child(3){color:red}

标签: html css colors html-table


【解决方案1】:

您可以简单地使用 nth-last-child 来设置 TD 的样式。 此代码将影响最后 4 项(将颜色变为红色):

td:nth-last-child(-n+4) {
    color: red;
}

这个让他们的背景变成红色:

td:nth-last-child(-n+4) {
        background: red;
    }

【讨论】:

  • 您错过了“基于价值”的部分。
【解决方案2】:

你不能不添加一个围绕 X 的类的元素。

<td><span class="redbg">x</span></td>

【讨论】:

    【解决方案3】:

    要获取它,您可以执行以下操作:

    第一个:在页面集类的开头

    .red {
        background: red;
    }
    

    第二个:然后放你表格和其他html代码

    3rd:在页面末尾使用 javascript 将 red 类应用于包含“x”的所有单元格:

    <script>
      var cells = document.getElementsByTagName("td");
      for (i=0; i<cells.length; i++) {
          if(cells[i].innerHTML == "x") cells[i].className = "red";
      }
    </script>
    

    下面是一个工作示例:

      var cells = document.getElementsByTagName("td");
      for (i=0; i<cells.length; i++) {
          if(cells[i].innerHTML == "x") cells[i].className = "red";
      }
    .red {
        background: red;
    }
    
    td{
      width: 80px;
    }
    <table>
        <tr>
            <td>Mini Contests</td>
            <td>5</td>
            <td>5.0</td>
            <td>x</td>
            <td>x</td>
            <td>x</td>
            <td>x</td>
        </tr>
    </table>

    【讨论】:

      猜你喜欢
      • 2019-11-12
      • 2014-05-04
      • 2023-04-07
      • 2022-12-08
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多