Chrome内置的JavaScript控制台可以显示颜色吗?

我想要错误在红色,警告在橙色和控制台。log在绿色。这可能吗?


当前回答

默认情况下,很少有内置的控制台方法来显示警告、错误和正常控制台以及特定的图标和文本颜色。

console.log(“console.log”); console.warn(“console.warn”); console.error(“console.error”);

但如果您仍然想应用自己的样式,您可以使用%c与消息和CSS样式规则作为第二个参数。

Console.log ('%cconsole.log', 'color:绿色;'); console.warn(“% cconsole。警告','颜色:绿色;'); console.error(“% cconsole。错误','颜色:绿色;');

注意:在运行上述代码段时,请在浏览器控制台中检查结果,而不是代码段结果。

其他回答

你可以试试:

console.log("%cI am red %cI am green", "color: red", "color: green");

输出:

我写了template-colors-web https://github.com/icodeforlove/Console.js,让我们更容易做到这一点

console.log(c`red ${c`green ${'blue'.bold}.blue`}.green`.red);

使用默认的console.log将很难做到以上这些。

现场互动演示点击这里。

看看这个:

控制台动画,加上CSS

(function() {
  var frame = 0;
  var frames = [
    "This",
    "is",
    "SPARTA!",
    " ",
    "SPARTA!",
    " ",
    "SPARTA!",
    " ",
    "SPARTA!",
    " ",
    "SPARTA!",
    " ",
    "SPARTA!"
  ];
  var showNext = () => {
    console.clear();
    console.log(
      `%c `,
      "background: red; color: white; font-size: 15px; padding: 3px 41%;"
    );
    console.log(
      `%c ${frames[frame]}`,
      "background: red; color: white; font-size: 25px; padding: 3px 40%;"
    );
    console.log(
      `%c `,
      "background: red; color: white; font-size: 15px; padding: 3px 41%;"
    );
    setTimeout(
      showNext,
      frames[frame] === "SPARTA!" || frames[frame] === " " ? 100 : 1500
    );
    // next frame and loop
    frame++;
    if (frame >= frames.length) {
      frame = 0;
    }
  };
  showNext();
})();

https://jsfiddle.net/a8y3jhfL/

你可以在每一帧中粘贴ASCII来观看ASCII动画

谷歌对此进行了记录 https://developers.google.com/web/tools/chrome-devtools/console/console-write#styling_console_output_with_css

CSS格式说明符允许您自定义控制台中的显示。使用说明符开始字符串,并给出希望应用的样式作为第二个参数。

一个例子:

console.log("%cThis will be formatted with large, blue text", "color: blue; font-size: x-large");

我写了一个npm模块,提供了通过的可能性:

自定义颜色-文本和背景; 前缀——帮助识别源代码,如[MyFunction] 类型——像警告、成功、信息和其他预定义的消息类型

https://www.npmjs.com/package/console-log-plus

输出(带有自定义前缀):

clp({
  type: 'ok',
  prefix: 'Okay',
  message: 'you bet'
});
clp({
  type: 'error',
  prefix: 'Ouch',
  message: 'you bet'
});
clp({
  type: 'warning',
  prefix: 'I told you',
  message: 'you bet'
});
clp({
  type: 'attention',
  prefix: 'Watch it!',
  message: 'you bet'
});
clp({
  type: 'success',
  prefix: 'Awesome!',
  message: 'you bet'
});
clp({
  type: 'info',
  prefix: 'FYI',
  message: 'you bet'
});
clp({
  type: 'default',
  prefix: 'No fun',
  message: 'you bet'
});

输出(不带自定义前缀):

输入:

clp({
  type: 'ok',
  message: 'you bet'
});
clp({
  type: 'error',
  message: 'you bet'
});
clp({
  type: 'warning',
  message: 'you bet'
});
clp({
  type: 'attention',
  message: 'you bet'
});
clp({
  type: 'success',
  message: 'you bet'
});
clp({
  type: 'info',
  message: 'you bet'
});
clp({
  type: 'default',
  message: 'you bet'
});

为了确保用户不会呈现无效的颜色,我还编写了一个颜色验证器。它将通过名称、十六进制、rgb、rgba、hsl或hsla值来验证颜色