console.log
最经常使用它在控制台输出信息然后进行代码调试,会发现输出信息的颜色永远是黑色。本文教学如何用 console.log
在控制台输出具有五彩斑斓颜色的信息。
单色输出
javascript
console.log('\x1B[31m红色\x1B[34m 蓝色')
![](https://file.jishuzhan.net/article/1778712432303149058/e455a66a2272b5a2452189f42936f0e7.webp)
javascript
console.log('%c字符:', 'color:red', type)
![](https://file.jishuzhan.net/article/1778712432303149058/2b5cf040130ac6ad50b0274a4613adec.webp)
javascript
console.log('%c当前环境:' + type, 'color:blue')
![](https://file.jishuzhan.net/article/1778712432303149058/24794b215ba73835e35d7f175a490469.webp)
多色输出
javascript
console.log('%c123%c456', 'color: blue', 'color: green')
console.log.apply(void 0, ['%c123%c456', 'color: blue', 'color: green'])
![](https://file.jishuzhan.net/article/1778712432303149058/965997c2776c5fb320a14655868381ff.webp)
背景输出
javascript
console.log('\x1b[43m背景')
![](https://file.jishuzhan.net/article/1778712432303149058/07f975331093ec76e90ddc631aa53241.webp)
背景+颜色输出
javascript
console.log('%c hello world ',
'background: black; color: red')
![](https://file.jishuzhan.net/article/1778712432303149058/bda73609b745dcc5c357530d73106259.webp)
背景+颜色+样式输出
javascript
console.log('%c 输出 %c 大大 a %c 颜色', 'color:red;', 'font-size:30px;', 'color:blue;background:yellow;')
![](https://file.jishuzhan.net/article/1778712432303149058/97bfa6793098ed32a1fe17c8205bb714.webp)
其他输出
warn输出:
javascript
console.warn('hello world')
![](https://file.jishuzhan.net/article/1778712432303149058/d5cd38000d07aa2bdd40a11ef55cb89f.webp)
error输出:
javascript
console.error('hello world')
![](https://file.jishuzhan.net/article/1778712432303149058/2afc17b9695d8a23aa7c8fee2c921d2d.webp)
body输出:
javascript
console.log('%o', document.body)
![](https://file.jishuzhan.net/article/1778712432303149058/475c843ba5b58a8be4b9fbf806c74741.webp)