在Chrome中使用console.log样式时,换行符无法正常工作

时间:2018-07-11 21:23:45

标签: css google-chrome console.log

我希望我不会做些愚蠢的事情,但我会在Chrome的devtools中写出来:

console.log('%c{\n  a: %c1 %c2%c,\n}', 'color:grey;', 
    'color:red;', 'color:green;', 'color:grey;');

并且我希望看到这个:

{
    a: 1 2,
}

但实际上我得到了:

{      ,
 a: 1 2 }

这对我来说绝对没有任何意义...?

enter image description here

2 个答案:

答案 0 :(得分:1)

好吧,似乎控制台中所有样式化的文本都是某种内联块,并排堆叠。

因此,实际上,如果我们将背景色添加到您的代码中,我们将能够看到您的文本的真实布局:

actual layout

因此,要获得所需的图像,似乎必须考虑这种“基于列”的布局。以您的示例为例,

console.log('%c{\n  a: \n}%c1\n  %c2\n %c,\n ', 'color: grey;', 'color: red;', 'color:green;', 'color:grey;');

这是上面代码的结果:

expected image

不幸的是,我找不到任何解决方案,无法将它们堆叠为块,而不是内联块。因此,似乎唯一的选择是对每行使用console.log()。如果对于生成一行至关重要,则可以编写一个函数,以\n个字符和console.log()字符串的每个部分来分隔此行。

答案 1 :(得分:0)

我最终遇到了一个类似的问题,试图在单个console.log语句中记录对象的多个属性,但样式设置为多行。

我想以 name-> value 格式记录属性,并且还用红色将值记录为易于阅读的内容。

所以我最终构建的是这个函数:

//Function to transform an object to a formated string and params
var generateColouredLogObject = obj => {
    var formatedString = ""
    var arrayParams = []

    Object.keys(obj)
        .map(key => {
            obj[key]
                .map(item => {
                    formatedString += "%c %s --> %c %s %c"
                    arrayParams.push("", item.tag, "color:red", item.value, "")
                })
            formatedString += " \n"
        })

    return {text: formatedString, params: arrayParams}
}

这样,这样的对象:

//the data we want to print 
//Its built one 'line' property as an array containing each of the items (pair tag-vaule) you want to print
var objToLog = {
    line1: [{ tag: "domain", value: window.document.domain }],
    line2: [{ tag: "protocol", value: window.document.location.protocol }, { tag: "pahtname", value: window.document.location.pathname }],
}

在执行以下代码时产生如下输出:

var output = generateColouredLogObject(objToLog)

console.log(output.text, ...output.params)

Dev Console output when executing code on this same page

对于您的示例,您应该构建适合您的方案的“ formatedString”和“ arrayParams”

希望有帮助