Chrome内置的JavaScript控制台可以显示颜色吗?
我想要错误在红色,警告在橙色和控制台。log在绿色。这可能吗?
Chrome内置的JavaScript控制台可以显示颜色吗?
我想要错误在红色,警告在橙色和控制台。log在绿色。这可能吗?
当前回答
选项1
// log-css.js v2
const log = console.log.bind()
const css = (text, options) => {
let cssOptions = ''
for (let prop in options) {
const value = options[prop]
prop = camelCaseToDashCase(prop)
cssOptions += `${prop}: ${value}; `
}
return [`%c${text}`, cssOptions.trim()]
function camelCaseToDashCase(value) {
return value.replace(/[A-Z]/g, matched => `-${matched.toLowerCase()}`)
}
}
例子:
log(...css('Example =P', {
backgroundColor: 'blue',
color: 'white',
// fontFamily: 'Consolas',
fontSize: '25px',
fontWeight: '700',
// lineHeight: '25px',
padding: '7px 7px'
}))
选项2
我现在创建log-css.js https://codepen.io/luis7lobo9b/pen/QWyobwY
// log-css.js v1
const log = console.log.bind();
const css = function(item, color = '#fff', background = 'none', fontSize = '12px', fontWeight = 700, fontFamily) {
return ['%c ' + item + ' ', 'color:' + color + ';background:' + background + ';font-size:' + fontSize + ';font-weight:' + fontWeight + (fontFamily ? ';font-family:' + fontFamily : '')];
};
例子:
log(...css('Lorem ipsum dolor sit amet, consectetur adipisicing elit.', 'rebeccapurple', '#000', '14px'));
其他回答
我发现你可以使用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" );
colors = {
reset: '\033[0m',
//text color
black: '\033[30m',
red: '\033[31m',
green: '\033[32m',
yellow: '\033[33m',
blue: '\033[34m',
magenta: '\033[35m',
cyan: '\033[36m',
white: '\033[37m',
//background color
blackBg: '\033[40m',
redBg: '\033[41m',
greenBg: '\033[42m',
yellowBg: '\033[43m',
blueBg: '\033[44m',
magentaBg: '\033[45m',
cyanBg: '\033[46m',
whiteBg: '\033[47m'
}
console.log('\033[31m this is red color on text');
console.log('\033[0m this is reset');
console.log('\033[41m this is red color on background');
我写了template-colors-web https://github.com/icodeforlove/Console.js,让我们更容易做到这一点
console.log(c`red ${c`green ${'blue'.bold}.blue`}.green`.red);
使用默认的console.log将很难做到以上这些。
现场互动演示点击这里。
旧版本的Chrome不允许你让console.log()以编程方式显示特定的颜色,但是调用console.error()会在错误行上放一个红色的X图标,并使文本变成红色,而console.warn()会让你变成黄色!图标。
然后,您可以使用控制台下面的All、Errors、Warnings和Logs按钮筛选控制台条目。
Firebug支持控制台的自定义CSS。从2010年开始,Chrome支持已经添加到Chrome 24。
console.log('%c Oh my heavens! ', 'background: #222; color: #bada55',
'more text');
当%c出现在第一个参数中的任何位置时,下一个参数将用作设置控制台行样式的CSS。进一步的参数被连接起来(一如既往)。
默认情况下,很少有内置的控制台方法来显示警告、错误和正常控制台以及特定的图标和文本颜色。
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。错误','颜色:绿色;');
注意:在运行上述代码段时,请在浏览器控制台中检查结果,而不是代码段结果。