Chrome内置的JavaScript控制台可以显示颜色吗?
我想要错误在红色,警告在橙色和控制台。log在绿色。这可能吗?
Chrome内置的JavaScript控制台可以显示颜色吗?
我想要错误在红色,警告在橙色和控制台。log在绿色。这可能吗?
当前回答
我写了template-colors-web https://github.com/icodeforlove/Console.js,让我们更容易做到这一点
console.log(c`red ${c`green ${'blue'.bold}.blue`}.green`.red);
使用默认的console.log将很难做到以上这些。
现场互动演示点击这里。
其他回答
在Chrome & Firefox(+31)中,您可以在console.log消息中添加CSS:
console.log('%c我的天哪!', '背景:#222;颜色:# bada55 ');
同样适用于在同一命令中添加多个CSS。
参考文献
MDN:样式化控制台输出 Chrome:控制台API参考
我写了template-colors-web https://github.com/icodeforlove/Console.js,让我们更容易做到这一点
console.log(c`red ${c`green ${'blue'.bold}.blue`}.green`.red);
使用默认的console.log将很难做到以上这些。
现场互动演示点击这里。
有一系列内置函数用于为控制台日志上色:
//For pink background and red text
console.error("Hello World");
//For yellow background and brown text
console.warn("Hello World");
//For just a INFO symbol at the beginning of the text
console.info("Hello World");
//for custom colored text
console.log('%cHello World','color:blue');
//here blue could be replaced by any color code
//for custom colored text with custom background text
console.log('%cHello World','background:red;color:#fff')
谷歌对此进行了记录 https://developers.google.com/web/tools/chrome-devtools/console/console-write#styling_console_output_with_css
CSS格式说明符允许您自定义控制台中的显示。使用说明符开始字符串,并给出希望应用的样式作为第二个参数。
一个例子:
console.log("%cThis will be formatted with large, blue text", "color: blue; font-size: x-large");
模板系统,有用的,如果你想创建彩色的行文本,而不为每个块创建完整的风格
var tpl = 'background-color:greenyellow; border:3px solid orange; font-size:18px; font-weight: bold;padding:3px 5px;color:';
console.log('%cMagenta %cRed %cBlue', `${tpl} magenta`, `${tpl} Red`,`${tpl} #4274fb`);