2017-07-31 143 views
1

我编写了一个简单的打印功能,可逐字母打印到控制台中。我也想打印出与严格使用Javascript不同颜色的文字,例如:如何设置打印到控制台的单个字的字体颜色

print("Hello", "green"); print(" World", "blue"); 

function print(word, color) 
    var console = document.getElementById("myConsole"); 
    console.style.color = color; 
    console.append(word); 

我想“你好”是绿色,“世界”是蓝色的,而是什么情况是,控制台打印用绿色表示“Hello”,然后用蓝色打印“World”,同时将“Hello”的颜色改为蓝色。

我有一个更详细的例子在这里:https://jsfiddle.net/Jsbbvk/vL8tLwfh/

是否有访问个别字的字体颜色的方法吗?

+0

所以你需要创建个人元素。 – epascarello

回答

0

创建另一个元素并将其附加到它。然后将该元素附加到控制台。

在下面的代码片段,我改变了变量名控制台,因为它已经在JavaScript中的意义

print("Hello", "green"); 
 
print(" World", "blue"); 
 
function print(word, color){ 
 
    var conso = document.getElementById("myConsole"); 
 
    var span = document.createElement('span'); 
 
    span.style.color = color; 
 
    span.append(word); 
 
    conso.append(span); 
 
}
<div id="myConsole"></div>

1

创建一个新的元素,色彩运用它,添加元素你的主元素,然后附加文字

function showText(message, color, index, interval, callback) { 
 
    if (index < message.length) { 
 
    \t var span = document.createElement('span'); 
 
    span.style.color = color; 
 
    document.getElementById("text_target").append(span); 
 
    span.append(message[index++]); 
 
    setTimeout(function() { 
 
     showText(message, color, index, interval, callback); 
 
    }, interval); 
 
    } else { 
 
    callback && callback(); 
 
    } 
 
} 
 

 

 
showText("HELLO", "green", 0, 200, function() { 
 
    showText(" DONE", "red", 0, 200); 
 
}); 
 
//Hello should be green and Done should be red 
 
//how do you set individual text colors?
<div id="msg" /> 
 
<span id="text_target"></span>

相关问题