如何在 JavaScript 中打印彩色文本到控制台?
在本文中,我们将学习如何向文本添加颜色并在 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>
广告