根据文本内容动态更改背景颜色

时间:2017-10-23 21:27:19

标签: javascript

我有一列GPA,我想基于3.00到4.00的文本内容动态着色。我希望3.00有蓝色背景,4.00有红色背景。

我在这里尝试过document.querySelectorAll,但它不起作用?

var colorList = document.querySelector('.colorList');

colorList.style.backgroundColor = '#74abe5';

// This is just to demonstrate what color I'd like the highest cell to be.

var colorListEnd = document.querySelector('.colorListEnd');

colorListEnd.style.backgroundColor = '#d7727d'

http://jsbin.com/razicenari/edit?html,js,output

我正在拍摄的视觉表现:https://imgur.com/a/GFD51

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

你去了:

var colorLists = document.querySelectorAll('.colorList');
for (let colorList of colorLists) {
    let value = Number(colorList.textContent),
        t = Math.min(1, Math.max(0, value - 3)),
        r = 116 * (1 - t) + 215 * t,
        g = 171 * (1 - t) + 114 * t,
        b = 229 * (1 - t) + 125 * t;

    colorList.style.backgroundColor = "rgb(" + (r | 0) + "," + (g | 0) + "," + (b | 0) + ")";
}

答案 1 :(得分:1)

你可以这样做:

function convertRange( value, r1, r2 ) { 
    return ( value - r1[ 0 ] ) * ( r2[ 1 ] - r2[ 0 ] ) / ( r1[ 1 ] - r1[ 0 ] ) + r2[ 0 ];
}

var colorList = document.querySelectorAll('.colorList');

colorList.forEach(function(color){
  var colorPicker = convertRange(color.innerText, [3.0, 4.0], [50, 200]);
  color.style.backgroundColor = "rgb(" + Math.floor(colorPicker) + ",20," + Math.floor(255 - colorPicker) + ")";
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<table class="table table-striped table-sm">
    <thead class="thead-inverse">
      <tr>

        <th>GPA** <br> 50%
        </th>
        <th>75%</th>
        <th>Max</th>
        <th>SAT Reading*** <br>25%-75%</th>
        <th>SAT Math*** <br>25%-75%</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="colorList">3.52</td>
        <td>3.80</td>
        <td>4.00</td>
        <td>400-510</td>
        <td>400-530</td>
      </tr>
      <tr>
        <td class="colorList">3.62</td>
        <td>3.80</td>
        <td>4.00</td>
        <td>400-510</td>
        <td>400-530</td>
      </tr>
      <tr>
        <td class="colorList">3.72</td>
        <td>3.80</td>
        <td>4.00</td>
        <td>400-510</td>
        <td>400-530</td>
      </tr>
      <tr>
        <td class="colorList">3.82</td>
        <td>3.80</td>
        <td>4.00</td>
        <td>400-510</td>
        <td>400-530</td>
      </tr>
      <tr>
        <td class="colorList">3.92</td>
        <td>3.80</td>
        <td>4.00</td>
        <td>400-510</td>
        <td>400-530</td>
      </tr>
    </tbody>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  </table>
</body>
</html>