首页 > 解决方案 > 更改从 Google 表格导入的正/负值的字体颜色

问题描述

这是我的代码,它允许我通过指定列标题从我的 Google 表格中导入。

function httpGetAsync(theUrl, callback) {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
      callback(xmlHttp.responseText);
  }
  xmlHttp.open("GET", theUrl, true); // true for asynchronous
  xmlHttp.send(null);
}

httpGetAsync('https://spreadsheet.glitch.me/?key=1JBbAHH1DFtO1r56lr94lUqd8H7qPcHncJskcPq0r96o', function(response) {
  var json = JSON.parse(response);

  document.getElementById("btm").innerHTML = json[0].btm;
  document.getElementById("AvgPoints").innerHTML = json[0].AvgPoints;
  document.getElementById("Overtakes").innerHTML = json[0].Overtakes;
  document.getElementById("podium").innerHTML = json[0].podium;
  document.getElementById("highest").innerHTML = json[0].highest;
});

这允许我放入<div id="AvgPoints"></div>我的 HTML 并根据我的 Google 表格文档中的值进行填充。我的目标是为正数(包括 0)和红色为负数的字体着色为绿色。<div></div>这是否可能考虑到我的 HTMl 代码中的标签之间实际上没有数字?如果是这样,我也有兴趣了解如何根据它是否为正/负来在导入的数字前面添加 +/- 字符。对不起,我正在努力学习。谢谢!

标签: javascriptjquerygoogle-sheetscolors

解决方案


只需将值转换为数字,检查正数或负数,然后您可以为元素分配一个预制的 CSS 类,并可能在前面加上适当的+符号(我假设它们前面已经有负值-)。

// Get all the divs that should be styled into an array
let divs = Array.prototype.slice.call(document.querySelectorAll("#btm, #AvgPoints, #Overtakes, #podium, #highest"));

// Loop the array
divs.forEach(function(div){
  // Convert text to number and test for positive/negative
  if((+div.textContent) >= 0){
    div.classList.add("positive"); // Apply positive style
    div.textContent = "+" + div.textContent; 
  } else {
    div.classList.add("negative"); // Apply negative style  
  }
});
.positive { color: green; }
.negative { color: red; }
<div id="btm">135</div>
<div id="AvgPoints">0</div>
<div id="Overtakes">-17</div>
<div id="podium">1</div>
<div id="highest">-125</div>


推荐阅读