今天看到一篇頗有意思的一篇文章,如何打印多彩的console.log? 前端的小夥伴對console.log再熟悉不過了,可是至今爲止,我都是一直在用其最普通的用法,控制檯中打印一條message。沒想到,還能給console.log應用樣式呢?不知道大家是否知道呢?css
console.log('%cHello', 'color: green; background: yellow: font-size: 30px');
複製代碼
能夠看出,上面的log語句由三部分組成: %c + message + style 其中標識符後緊跟message, 第二個參數爲樣式 最後輸出的message的效果就如樣式所定義的一致。前端
當遇到一個具備大量log輸出的大型應用時,若是在一些比較重要的地方輸出帶樣式的log時,你能夠在控制檯中快速發現它,不至於淹沒在一堆的log中難以發現查找。數組
console.log(
'Nothing here %cHi Cat %cHey Bear', // Console Message
'color: blue', 'color: red' // CSS Style
);
複製代碼
效果以下圖,標識符前面的文本不受影響。 bash
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;');
複製代碼
// 1. 將css樣式內容放入數組
const styles = [
'color: green',
'background: yellow',
'font-size: 30px',
'border: 1px solid red',
'text-shadow: 2px 2px black',
'padding: 10px',
].join(';');
// 2. 利用join方法講各項以分號鏈接成一串字符串
// 3. 傳入styles變量
console.log('%cHello There', styles);
複製代碼
甚至,你還能把須要輸出的message也抽離出來,保存在變量中spa
const styles = ['color: green', 'background: yellow'].join(';');
const message = 'Some Important Message Here';
// 3. 傳入styles和message變量
console.log('%c%s', styles, message);
複製代碼
參考文章 medium.com/@samanthami…debug
喜歡的點贊支持下哦!code