
在
console
裡添加
%c
說明符??。這可以幫助你很容易找到你要列印的日志?。特别是在一個有着成千上萬個日志的大型應用中,給你的日志加上樣式,就不會讓你重要的日志埋沒。或者說,這可以提醒人們離開控制台。就像在facebook網站中,你打開控制台,會見到一個大大的紅色的Stop!。現在你應該懂得它的用處了?。
// 在你的浏覽器裡的控制台輸入
console.log('%cHello', 'color: green; background: yellow; font-size: 30px');
複制
%c
是什麼
%c
你可以使用
%c
為列印内容定義樣式,在它之前的内容不會被影響,而會影響後面的内容。
使用多個樣式
想要使用多個樣式,你隻需在你想要的日志前加上
%c
。在這之後的日志就會根據後面樣式的順序顯示。
console.log(
'Nothing here %cHi Cat %cHey Bear', // Console 日志
'color: blue', 'color: red' // CSS 樣式
);
複制
為其他的 console
加樣式
console
還有5種方式列印日志:
-
console.log
-
console.info
-
console.debug
-
console.warn
-
console.error
同樣的,你也可以為他們加上樣式。
console.log('%cconsole.log', 'color: green;');
console.info('%cconsole.info', 'color: blue;');
console.debug('%cconsole.debug', 'color: yellow;');
console.warn('%cconsole.warn', 'color: fuchsia;');
console.error('%cconsole.error', 'color: red;');
複制
使用數組傳入 CSS 樣式
當你的樣式比較複雜的時候,用字元串表示樣式會特别長。有個漂亮的寫法是用數組和
join()
方法連成字元串。
// 1. 用數字儲存
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);
複制
結合 %s
一起使用
%s
同樣也可以結合
%s
一起使用。
const styles = ['color: green', 'background: yellow'].join(';');
const message = 'Some Important Message Here';
// 3. 傳入樣式和日志
console.log('%c%s', styles, message);
複制