发布于 2026-01-06 6 阅读
0

如何在 Chrome Dev Tools 中设置 console.log 的样式?DEV 的全球展示挑战赛,由 Mux 呈现:展示你的项目!

如何在 Chrome 开发者工具中设置 console.log 的样式

由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!

如果你和我一样,习惯console.log用控制台输出信息来进行调试,那么我们至少可以做的就是让输出更美观。如果我们的日志能像下面的屏幕截图那样,用不同的颜色和字体大小打印出来,岂不是很棒?

替代文字

为了设置日志样式(格式),我们必须使用所谓的 `<style>` 标签format specifiers。它们包含%符号 `<style>`,后跟一个字母,该字母指定我们要应用于输出的格式类型。

它们长这样:

%s - Formats the value as a string
%i or %d - Formats the value as an integer
%f - Formats the value as a floating point value
%o - Formats the value as an expandable DOM element. As seen in the Elements panel 
%O - Formats the value as an expandable JavaScript object
%c - Applies CSS style rules to the output string as specified by the second parameter
Enter fullscreen mode Exit fullscreen mode

现在,我们来写一些例子。你可以把它们复制粘贴到Chrome控制台中,看看结果。

示例:打印blue string(应用 CSS 样式)

console.log("%cThis will be formatted with blue text", "color: blue"); 
// outputs: This will be formatted with blue text [in blue color]
Enter fullscreen mode Exit fullscreen mode

我们可以添加任意数量的样式

console.log("%cTry me on!", "color: #FFFFFF; font-size: 45px; background: #333333; text-shadow: #FFF 0px 0px 5px, #FFF 0px 0px 10px, #FFF 0px 0px 15px, #FF2D95 0px 0px 20px, #FF2D95 0px 0px 30px, #FF2D95 0px 0px 40px, #FF2D95 0px 0px 50px, #FF2D95 0px 0px 75px;")
// outputs: a Vegas style super shiny string
Enter fullscreen mode Exit fullscreen mode

样式并不是我们在控制台中唯一可以操作的内容。我们还可以转换数据类型(例如将数字转换为字符串)或输出数据类型(例如打印对象或浮点数)。请查看以下示例。

示例:打印string(将数字转换为字符串)

console.log("This will be formatted as a string - %s ", 8999); 
// outputs: This will be formatted as an integer - 8999 
Enter fullscreen mode Exit fullscreen mode

示例:打印数组string(将数组转换为字符串)

console.log("This will be formatted as a string - %s ", [78, 89, 1024, 47]); 
// outputs: This will be formatted as a string - Array(4) 
Enter fullscreen mode Exit fullscreen mode

你实际上无法与控制台中的输出进行交互,因此你无法看到数组的内容,因为它只是一个字符串。

示例:打印一个object

console.log('This is an object %o', { obj: { prop1: 'Hello', prop2: "World" }})
// outputs: this is an object {obj: {…}}
Enter fullscreen mode Exit fullscreen mode

您可以在控制台中与输出进行交互,展开对象并查看其属性。

例如:打印一个integer或一个float

console.log('Integer: %d, Floating point: %.1f', 12, 7.3)
// output: Integer: 12, Floating point: 7.3
Enter fullscreen mode Exit fullscreen mode

LATER EDIT - grouping specifiers

如果要同时使用多个格式说明符,可以这样做:

console.log("%cThis will be formatted with blue text This will be formatted as a string - %s", "color: blue", 8999)
// outputs: This will be formatted with blue text This will be formatted as a string - 8999 [all in blue color]
Enter fullscreen mode Exit fullscreen mode

我们基本上是在第一个字符串中提供所有格式说明符,然后arguments逐个提供逗号(是否用引号取决于您要实现的目标——例如,CSS 规则和字符串需要引号,数字或数组则不需要)。

文章来源:https://dev.to/arikaturika/how-to-style-console-logs-in-chrome-dev-tools-33np