Chrome内置的JavaScript控制台可以显示颜色吗?
我想要错误在红色,警告在橙色和控制台。log在绿色。这可能吗?
Chrome内置的JavaScript控制台可以显示颜色吗?
我想要错误在红色,警告在橙色和控制台。log在绿色。这可能吗?
当前回答
谷歌对此进行了记录 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");
其他回答
我最近想解决一个类似的问题,构造了一个小函数,只对我关心的关键字进行着色,这些关键字很容易通过周围的花括号{keyword}识别。
这招很管用:
var text = 'some text with some {special} formatting on this {keyword} and this {keyword}'
var splitText = text.split(' ');
var cssRules = [];
var styledText = '';
_.each(splitText, (split) => {
if (/^\{/.test(split)) {
cssRules.push('color:blue');
} else {
cssRules.push('color:inherit')
}
styledText += `%c${split} `
});
console.log(styledText , ...cssRules)
从技术上讲,您可以用switch/case语句替换if语句,以允许根据不同的原因使用多种样式
默认情况下,很少有内置的控制台方法来显示警告、错误和正常控制台以及特定的图标和文本颜色。
console.log(“console.log”); console.warn(“console.warn”); console.error(“console.error”);
但如果您仍然想应用自己的样式,您可以使用%c与消息和CSS样式规则作为第二个参数。
Console.log ('%cconsole.log', 'color:绿色;'); console.warn(“% cconsole。警告','颜色:绿色;'); console.error(“% cconsole。错误','颜色:绿色;');
注意:在运行上述代码段时,请在浏览器控制台中检查结果,而不是代码段结果。
你可以试试:
console.log("%cI am red %cI am green", "color: red", "color: green");
输出:
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`);