简化的控制台日志记录

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

1
重复的问题?https://dev59.com/Z37aa4cB1Zd3GeqPlhR8。或者至少我认为是这样做的。 - Felix Kling
3个回答

55

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

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

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');

Displaying an image on console log


2
适用于Chrome 54.0.2840.100(64位) - Eugene Pankov
3
+1 对于背景图片示例。你有什么想法为什么它也记录了“未定义”?我似乎无法摆脱它。 - Tim Cooke
3
尝试使用'%c ',注意空格。看起来是因为您没有渲染任何文本,所以它没有要应用样式的内容。 - Keith
1
示例会将图像记录到控制台两次,不太确定原因。使用的是Chromium 71。 - Anticom
2
不错,它可以工作。在我的情况下,我有两个图像(重复)。你有什么想法为什么会这样? - Andrea_86
显示剩余3条评论

3

对于那些有两张重复图片的人,像@BayyMekenique所说,添加背景 no-repeat,但也要更改这一行:

code 'line-height: ' + this.height + 'px;', code

更改为:

code 'line-height: ' + this.height % 2 + 'px;', code

enter image description here


这个停止工作了,有什么想法为什么? - Wonay

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接