Chrome内置的JavaScript控制台可以显示颜色吗?
我想要错误在红色,警告在橙色和控制台。log在绿色。这可能吗?
Chrome内置的JavaScript控制台可以显示颜色吗?
我想要错误在红色,警告在橙色和控制台。log在绿色。这可能吗?
当前回答
模板系统,有用的,如果你想创建彩色的行文本,而不为每个块创建完整的风格
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`);
其他回答
我写了template-colors-web https://github.com/icodeforlove/Console.js,让我们更容易做到这一点
console.log(c`red ${c`green ${'blue'.bold}.blue`}.green`.red);
使用默认的console.log将很难做到以上这些。
现场互动演示点击这里。
我发现你可以使用ANSI颜色代码制作带有颜色的日志,这使得在调试中更容易找到特定的消息。试一试:
console.log( "\u001b[1;31m Red message" );
console.log( "\u001b[1;32m Green message" );
console.log( "\u001b[1;33m Yellow message" );
console.log( "\u001b[1;34m Blue message" );
console.log( "\u001b[1;35m Purple message" );
console.log( "\u001b[1;36m Cyan message" );
谷歌对此进行了记录 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");
const coloring = fn => ({ background, color = 'white' }) => (...text) => fn(`%c${text.join('')}`, `color:${color};background:${background}`); const colors = { primary: '#007bff', success: '#28a745', warning: '#ffc107', danger: '#dc3545', info: '#17a2b8', }; const dir = (key = '', value = {}) => { logs.primary(`++++++++++++start:${key}++++++++++++++`); console.dir(value); logs.primary(`++++++++++++end:${key}++++++++++++++`); }; const logs = Object.keys(colors) .reduce((prev, curr) => ({ ...prev, [curr]: coloring(console.log)({ background: colors[curr] }) }), { dir }); logs.success('hello succes'); logs.warning('hello fail');
我怀疑是否有人会真正看到它,但对于那些想要在同一条线上混合几种颜色的人,我有一个简单的解决方案:
export enum Colors {
Black = '\033[30m',
Red = '\x1b[31m',
Green = '\x1b[32m',
Yellow = '\x1b[33m',
Blue = '\033[34m',
Magenta = '\033[35m',
Cyan = '\033[36m',
White = '\033[37m'
}
function color(text: string, color: color: Colors) {
return `${color}${text}\x1b[0m`;
}
console.log(`This is ${color('green text', Colors.Green)} but this is black. This is red ${color('red', Colors.Red)} etc`);