查找 console.log("%cText", "css:value") 的其他语法

Finding other syntaxes for console.log("%cText", "css:value")

我刚刚通过在包含 CSS 的 console.log(...) 中添加第二个参数,在控制台中发现 it's possible to do magic格式化。诀窍是在文本前加上 %c。例如,以下内容。

const text = "I am feeling blue";
const css = "color: orange;";
console.log("%c" + text, css);

虽然偶尔拥有它非常好,但我不禁想知道从书呆子的深入研究角度来看 %something 语法是否还有更多内容。

我猜 c 代表 css 并且百分号是某种转义字符我没有被意识到。我也 googled 那个,但由于使用的语法,有点难以指定我要查找的内容。而且,众所周知,Google 读心术很烂。

这个问题是双重的。还有哪些其他语法可用于控制台日志记录,尤其是百分号(这似乎是一个工具类的东西)and/or我如何google自己研究这些东西?

Console Namespace 其中包括所有功能定义 https://console.spec.whatwg.org/

另一个有用的link https://developer.mozilla.org/en-US/docs/Web/API/console

其他%语法包括

%o or %O    Outputs a JavaScript object. Clicking the object name opens more information about it in the inspector.
%d or %i    Outputs an integer. Number formatting is supported, for example  console.log("Foo %.2d", 1.1) will output the number as two significant figures with a leading 0: Foo 01
%s  Outputs a string.
%f Outputs a floating-point value. Formatting is supported, for example  console.log("Foo %.2f", 1.1) will output the number to 2 decimal places: Foo 1.10

CSS 造型

立即测试

您可以 运行 通过检查 Whosebug 并在控制台部分输入此命令并按回车键来 运行 此命令

console.log("This is %cWhosebug", "color: yellow; font-style: italic; background-color: blue;padding: 2px");

控制台格式说明符

如何运作?控制台格式说明符包含符号 %,在指定我们编写应应用于该值的格式类型的字母之后。

我们可以将第二个参数传递给 console.log,因为效果会按相应的顺序在字符串消息上发生变化,或者将值插入到输出字符串中。

控制台格式说明符列表和各自的输出

Console Specifier     Output 
 %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

例如 运行 控制台中的这一行:

const text = "This is a default font style";

console.log("%c" + text,"color: blue; font-size: 20px");
console.log("Hi %s, my name is %s", 'world', 'Joe',);
console.log(
'Hello %cAlligator%c!',
'color: #008f68; font-weight: bold; font-size: 2rem; text-shadow: 0 0 5px rgba(0,0,0,0.2);',
'color: hotpink; font-weight: bold; font-size: 2rem; text-shadow: 0 0 5px rgba(0,0,0,0.2);'
);

var a = [34, 203, 3, 746, 200, 984, 198, 764, 9];
console.log('myFunc(%o)', a);


console.log('%c' + text, 'font-weight: bold; font-size: 50px;color: red; text-shadow: 3px 3px 0 rgb(217,31,38) , 6px 6px 0 rgb(226,91,14) , 9px 9px 0 rgb(245,221,8) , 12px 12px 0 rgb(5,148,68) , 15px 15px 0 rgb(2,135,206) , 18px 18px 0 rgb(4,77,145) , 21px 21px 0 rgb(42,21,113)');

要了解更多信息,请查看 official documentation