js点击标签后背景颜色改变_(原创)Node.JS实战41:让命令行变的五颜六色!

通常情况下,命令行文字都是黑底白色的:

b9ea863a5fb02c698b5e68107d9c42d7.png

想不想来点改变?

0bbeb82b6b12e25bf0b455ca45710797.png

给文字换个颜色;给背景换个颜色。

先来看段代码:

console

想想它的运行输出是什么样的?

13b3bdb1474c7948804820120654329b.png

猜想到是这个效果了吗?想必没有吧。

为什么看似乱码的一段console()执行时会出现彩色的文字呢?

解释是这样的:

The original specification only had 8 colors, and just gave them names. The SGR parameters 30-37 selected the foreground color, while 40-47 selected the background. Quite a few terminals implemented "bold" (SGR code 1) as a brighter color rather than a different font, thus providing 8 additional foreground colors. Usually you could not get these as background colors, though sometimes inverse video (SGR code 7) would allow that. Examples: to get black letters on white background use ESC[30;47m, to get red use ESC[31m, to get bright red use ESC[31;1m. To reset colors to their defaults, use ESC[39;49m (not supported on some terminals), or reset all attributes with ESC[0m.
SGR code

大意是:“u001b”是一个特殊的转意字符,遵从一定的规则,可以用来设置文字或背景颜色。

上面代码中,前面的u001b[31m用于设定SGR颜色,后面的u001b[0m相当于一个封闭标签作为前面SGR颜色的作用范围的结束点标记。

那么,我们就知道文字变色的原因了。可是如何知道哪个具体的转义字符代表是的什么颜色呢?

下面的操作将进行展示,通过node.js的三方库源码找出答案,熟练掌握此方法将会使你将来大受裨益。

继续:

在Node.JS中,还有一些三方模块,可以实现同样的效果,比如:colors。

例程:

require

运行输出效果:

809c4d9b7c6ea80d93678854cf9a49c8.png

当安装这个模块后,它的源码就被下载到了本地:

377f851f2acac6a9db5bf7808bbcea5d.png

打开这个文件,在代码中会看到:

1fc5027ec57c86787d39be1708b8e10e.png

这下就找道相应颜色的转义字符了。这就是所谓的站在“巨人”的肩膀上吧。

更多本系列文章?传送门:

WangLiwen's Node.JS in practice​www.fairysoftware.com
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值