给 console 添加颜色

本文介绍如何使用%c声明为浏览器控制台输出添加CSS样式,包括为不同类型的日志设置样式,以及在Node.js环境中使用ColorReference设置样式的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简评:使用 %c 声明可以给 console 的输出添加 CSS 样式,日志太多的话,给不同种类的日志设置不同的样式,可以极大的提升阅读体验。

什么是 %c

%c: 标识将 CSS 样式应用于 %c 之后的 console 消息。

给 console 消息设置多个样式

可以给同一条 Console 消息设置多种颜色。

console.log(
  'Nothing here %cHi Cat %cHey Bear',  // Console Message
  'color: blue', 'color: red' // CSS Style
);

给其他 console 消息设置样式

这里有五种 console 类型的消息:

  • console.log
  • console.info
  • console.debug
  • console.warn
  • console.error

你可以自定义自己的日志样式,例如:

console.log('%cconsole.log', 'color: green;'); 
console.info('%cconsole.info', 'color: green;'); 
console.debug('%cconsole.debug', 'color: green;'); 
console.warn('%cconsole.warn', 'color: green;'); 
console.error('%cconsole.error', 'color: green;'); 

处理多种 CSS 样式

如果要输出的样式比较多,字符串会比较长,这里有一个小技巧, 生成一个 CSS Array ,通过 join(’;’) 来合并成一个 CSS String。

例如:

// 1.将css样式传递给数组
const styles = [ 
  'color:green',
  'background:yellow',
  'font-size:30px',
  'border:1px solid red',
  'text-shadow:2px 2px black',
  'padding:10px',
]。join(';'); // 2.连接单个数组项并将它们连接成一个用分号分隔的字符串(;)
// 3.传递样式变量
console.log('%cHello There',styles);
// or
console.log('%c%s', styles, 'Some Important Message Here');

在 Node.js 中设置 console 消息样式

在 node.js 环境,你可以使用 Color Reference 来设置样式。例如:

// Cyan
console.log('\x1b[36m%s\x1b[0m', 'I am cyan');
// Yellow
console.log('\x1b[33m%s\x1b[0m', 'yellow' );

原文:  Colorful Console Message

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值