Chrome内置的JavaScript控制台可以显示颜色吗?
我想要错误在红色,警告在橙色和控制台。log在绿色。这可能吗?
Chrome内置的JavaScript控制台可以显示颜色吗?
我想要错误在红色,警告在橙色和控制台。log在绿色。这可能吗?
当前回答
默认情况下,很少有内置的控制台方法来显示警告、错误和正常控制台以及特定的图标和文本颜色。
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。错误','颜色:绿色;');
注意:在运行上述代码段时,请在浏览器控制台中检查结果,而不是代码段结果。
其他回答
看看这个:
控制台动画,加上CSS
(function() {
var frame = 0;
var frames = [
"This",
"is",
"SPARTA!",
" ",
"SPARTA!",
" ",
"SPARTA!",
" ",
"SPARTA!",
" ",
"SPARTA!",
" ",
"SPARTA!"
];
var showNext = () => {
console.clear();
console.log(
`%c `,
"background: red; color: white; font-size: 15px; padding: 3px 41%;"
);
console.log(
`%c ${frames[frame]}`,
"background: red; color: white; font-size: 25px; padding: 3px 40%;"
);
console.log(
`%c `,
"background: red; color: white; font-size: 15px; padding: 3px 41%;"
);
setTimeout(
showNext,
frames[frame] === "SPARTA!" || frames[frame] === " " ? 100 : 1500
);
// next frame and loop
frame++;
if (frame >= frames.length) {
frame = 0;
}
};
showNext();
})();
https://jsfiddle.net/a8y3jhfL/
你可以在每一帧中粘贴ASCII来观看ASCII动画
我发现你可以使用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" );
几年前,我为自己写了一个非常非常简单的插件:
要添加到你的页面,你所需要做的就是把这个放在头部:
<script src="https://jackcrane.github.io/static/cdn/jconsole.js" type="text/javascript">
然后在JS中:
jconsole.color.red.log('hellllooo world');
该框架有以下代码:
jconsole.color.red.log();
jconsole.color.orange.log();
jconsole.color.yellow.log();
jconsole.color.green.log();
jconsole.color.blue.log();
jconsole.color.purple.log();
jconsole.color.teal.log();
以及:
jconsole.css.log("hello world","color:red;");
对于任何其他css。上面的代码是用以下语法设计的:
jconsole.css.log(message to log,css code to style the logged message)
旧版本的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。进一步的参数被连接起来(一如既往)。
如果你想给你的终端控制台上色,那么你可以使用npm包粉笔
npm i chalk