document.getElementById(“”)。innerHTML输出字体颜色

时间:2015-11-14 21:28:04

标签: javascript html arrays

我有一个循环遍历简单数据值数组的代码并将其打印出来以便

<div id = "output"> Output Updates </div> 
<div id = "track"> Track </div> 
<div id = "results"> Results <br/></div>

var output = document.getElementById("output");

var data = [12, 22, 01, 8, 34];
var dataIndex = 0;
var counter = 0; // Trial 
var current = 0;
var previous = data[0];

var output = document.getElementById("output");

setInterval(function() {
    //output.innerHTML = data[dataIndex].x;
    current = data[dataIndex];
    output.innerHTML = current;
    if (current > previous){
        document.getElementById("results").innerHTML += + current + " <br/>";
    }
    else if (current == previous) {
        document.getElementById("results").innerHTML += + current + " <br/>";
    }
    else {
        document.getElementById("results").innerHTML += + current + " <br/>";
    }

    previous = current;
    dataIndex = (dataIndex + 1) % data.length;

}, 500)

我想做的是 如果(当前&gt;上一个)条件,则以绿色字体打印结果 否则if(current == previous)condition,然后以黑色字体打印结果 else条件,然后以红色字体打印结果

当我为每个条件设置字体颜色样式时,它会更改已打印的每个结果的字体颜色

这是一个jsfiddle链接https://jsfiddle.net/kmhz6kx0/

1 个答案:

答案 0 :(得分:0)

元素的直接文本节点只能有一种颜色,但其子颜色可以有不同的颜色。

每次更新div时都添加所需颜色的results

if (current > previous) {
  color= 'green';
}
else if (current == previous) {
  color= 'black';
}
else {
  color= 'red';
}

document.getElementById("results").innerHTML += 
  '<div style="color: '+color+'">' +current + " </div>";

Fiddle