在本文中,我们将学习如何向文本添加颜色并在 javascript 的控制台窗口中打印它们。在原来的版本中,控制台中打印的所有数据都是黑色的,没有其他颜色反映在控制台中,但在这里我们将添加一些带有文本的特殊字符,使我们的控制台窗口看起来更加丰富多彩。
有一些特殊代码可以帮助更改控制台窗口中输出的颜色,这些代码称为 ansi 转义代码。通过在 console.log() 方法中添加这些代码,我们可以在输出中看到多种颜色。
所有颜色的特殊代码如下 -
black = "\x1b[30m"red = "\x1b[31m"green = "\x1b[32m"yellow = "\x1b[33m"blue = "\x1b[34m"magenta = "\x1b[35m"cyan = "\x1b[36m"white = "\x1b[37m"
要实现向控制台窗口添加彩色文本的任务,我们需要先创建一个对象,然后在对象中添加带有颜色名称及其代码的键值对,即颜色名称为键,颜色为颜色代码作为特定键的值。添加键值对后,我们需要使用 for 循环打印这些键值对。
语法const color = {};color.black ="\x1b[30m";color.red = "\x1b[31m";color.green = "\x1b[32m";color.yellow = "\x1b[33m";color.blue = "\x1b[34m";color.magenta = "\x1b[35m";color.cyan = "\x1b[36m";color.white = "\x1b[37m";for (var key in color){ console.log( color[key] + key);}
示例在控制台中打印彩色文本在下面的示例中,我们在控制台中打印彩色文本。请先打开控制台,然后再单击“彩色文本”按钮。
<!doctype html><html><body> <center> <h1> javascript console colored text </h1> <p> please open the <b>console</b> to see the colored text. </h4> <p> click "colored text" to display colored text in the console.</p> <button onclick="colorfunc()">colored text</button> </center> <script> function colorfunc() { const color = {}; // assigning the key: value pair to an object color.black = "\x1b[30m"; color.red = "\x1b[31m"; color.green = "\x1b[32m"; color.yellow = "\x1b[33m"; color.blue = "\x1b[34m"; color.magenta = "\x1b[35m"; color.cyan = "\x1b[36m"; color.white = "\x1b[37m"; // to print the key-value pairs of the object for (var key in color) { console.log(color[key] + key); } } </script></body></html>
在这里您可以看到,在 for 循环中,我们首先打印了值,然后打印了键,因为要打印彩色文本,您必须将颜色代码放在实际文本之前。
注意 - 我们有文本的颜色代码,类似地,我们有背景文本的颜色代码,如果我们想要控制台窗口中的彩色背景,我们可以使用它们。背景颜色的颜色代码如下 -
bgblack = "\x1b[40m"bgred = "\x1b[41m"bggreen = "\x1b[42m"bgyellow = "\x1b[43m"bgblue = "\x1b[44m"bgmagenta = "\x1b[45m"bgcyan = "\x1b[46m"bgwhite = "\x1b[47m"
示例在控制台中设置文本背景颜色在下面的示例中,我们在控制台中设置文本背景颜色。在执行程序之前,请确保您已打开控制台。
<!doctype html><html><body> <center> <h2> javascript console colored text background </h2> <p> please open the <b>"console"</b> to see the colored text background. </p> <p> click "colored text" to display colored text background in the console.</p> <button onclick="colorfunc()">colored text</button> </center> <script> function colorfunc() { const color = {}; // assigning the key: value pair to an object color.bgblack = "\x1b[40m" color.bgred = "\x1b[41m" color.bggreen = "\x1b[42m" color.bgyellow = "\x1b[43m" color.bgblue = "\x1b[44m" color.bgmagenta = "\x1b[45m" color.bgcyan = "\x1b[46m" color.bgwhite = "\x1b[47m" // to print the key-value pairs of the object for (var key in color) { console.log(color[key] + key); } } colorfunc() </script></body></html>
以上就是如何使用 javascript 在控制台中打印彩色文本?的详细内容。