javascript - 更改从 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 代码中的标签之间实际上没有数字?如果是这样,我也有兴趣了解如何根据它是否为正/负来在导入的数字前面添加 +/- 字符。对不起,我正在努力学习。谢谢!
解决方案
只需将值转换为数字,检查正数或负数,然后您可以为元素分配一个预制的 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>
推荐阅读
- java - 应用更新后Android webview缓存丢失
- flutter - 如何在颤动中使用来自另一个类的字符串数据
- snowflake-cloud-data-platform - Snowflake 支持哪些数据源?
- google-sheets - Google表格有没有办法将数组保存在单个单元格中并使用索引来查找矩阵的值?
- c++ - 关闭窗口时QTimer不会停止
- ldap - ActiveMQ JNDI/LDAP 错误
- flutter - 从给定的两个列表中,如何从一个列表中提取 Dart 中另一个列表中不可用的所有元素?
- python - 使用 Numpy 有效地按行排列数组
- payment-gateway - 使用 checkout.js 版本 61 的支付网关失败
- javascript - 禁用按钮的功能仅在与其并行运行的功能处于活动状态时生效