所属分类:web前端开发
在本文中,我们将学习如何向文本添加颜色并在 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>