程式化的控制台记录

cor*_*ore 19 javascript console

当我在Facebook上并打开控制台时,我在下面看到这张图片.他们如何做到这一点?

在此输入图像描述

小智 39

就像在Firebug中一样,您可以使用%c样式控制台日志输出.看看我们如何实现Facebook的例子:

console.log("%cStop!", "color: red; font-family: sans-serif; font-size: 4.5em; font-weight: bolder; text-shadow: #000 1px 1px;");
Run Code Online (Sandbox Code Playgroud)

Facebook的例子

由于它支持CSS属性,我们甚至可以在那里"绘制"图像:

(function(url) {
  // Create a new `Image` instance
  var image = new Image();

  image.onload = function() {
    // Inside here we already have the dimensions of the loaded image
    var style = [
      // Hacky way of forcing image's viewport using `font-size` and `line-height`
      'font-size: 1px;',
      'line-height: ' + this.height + 'px;',

      // Hacky way of forcing a middle/center anchor point for the image
      'padding: ' + this.height * .5 + 'px ' + this.width * .5 + 'px;',

      // Set image dimensions
      'background-size: ' + this.width + 'px ' + this.height + 'px;',

      // Set image URL
      'background: url('+ url +');'
     ].join(' ');

     // notice the space after %c
     console.log('%c ', style);
  };

  // Actually loads the image
  image.src = url;
})('https://i.cloudup.com/Zqeq2GhGjt-3000x3000.jpeg');
Run Code Online (Sandbox Code Playgroud)

在控制台日志上显示图像

  • 可悲的是,背景图像技巧似乎不再适用于Chrome ... (3认同)
  • @Olivier尝试做 - >''%c'`,注意空格.我看起来因为你没有渲染任何文字,所以它没有任何风格. (3认同)
  • 适用于Chrome 54.0.2840.100(64位) (2认同)
  • +1 用于背景图像示例。知道为什么它还记录“未定义”吗?我似乎无法摆脱它。 (2认同)
  • 很好,它有效。就我而言,我有 2 个图像(重复)。知道为什么吗? (2认同)