今天我在 Facebook 的 Chrome 浏览器中“摇摇晃晃”地走着。 出乎意料的是,我在控制台收到了这条信息。 现在我的问题是: 这怎么可能 我知道控制台有一些“利用”方法,但是如何在控制台中进行这样的字体格式设置呢?(是 console. log 吗?)
Try this:
console.log("%cThis will be formatted with blue text", "color: blue");
Quoting the docs,
You use the %c format specifier to apply custom CSS rules to any string you write to the Console with console.log() or related methods.
Source: https://developers.google.com/web/tools/chrome-devtools/console/console-write#styling_console_output_with_css
Yes, you can format the console.log() with something like this:
console.log()
console.log("%cExtra Large Yellow Text with Red Background", "background: red; color: yellow; font-size: x-large");
Note the %c preceding the text in the first argument and the style specifications in the second argument. The text will look like your example.
%c
See Google's "Styling Console Output with CSS" or FireBug's Console Documentation for more details.
The documentation links also include some other neat tricks like including object links in a console log as well.
From Google's website: site
console.log("%cThis will be formatted with large, blue text", "color: blue; font-size: x-large");
You can also format substrings.
var red = 'color:red'; var blue = 'color:blue'; console.log('%cHello %cWorld %cfoo %cbar', red, blue, red, blue);
Just extending other answers and you can reuse the existing css style of selector, class, element. Try this in SO console window.
const customLog = (message, cssSelector) => console.log( `%c${message}`, Object.entries(getComputedStyle(document.querySelector(cssSelector))) .map(([k, v]) => `${k}:${v}`) .join(";") ); customLog("Hello StackOverflow", "#question-header > div > a"); customLog("Hello StackOverflow", "strong"); customLog("Hello StackOverflow", "a");