【问题标题】:Newline not working correctly when using with console.log styling in chrome在 Chrome 中使用 console.log 样式时,换行符无法正常工作
【发布时间】:2018-12-20 00:27:19
【问题描述】:

我希望我没有做一些愚蠢的事情,但我正在 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 }

这对我来说完全没有意义......?

【问题讨论】:

    标签: css google-chrome console.log


    【解决方案1】:

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

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

    因此,要获得您想要的图像,您似乎必须考虑这种“基于列”的布局。对于您的示例,它将是:

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

    这是上面代码的结果:

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

    更新 Chrome 中的错误已修复,OP 的代码现在在 Chrome 89.0.4389.90 中按预期工作

    【讨论】:

    • 谢谢,这就是我目前所做的,但似乎很奇怪,之前似乎没有人遇到或提到过这一点。它也不在 chrome 开发者工具文档中。
    • 这之前没有提到,因为它曾经按预期工作,但目前在给出显示结果的格式中存在错误。
    • 谢谢,@Quentin2,这是很有价值的信息。是否有任何关于此的错误报告?
    • 我也很想知道这方面的任何错误报告。几周前它对我有用,但现在它似乎坏了。旁注:Firefox 可以很好地处理我的 console.logs。
    【解决方案2】:

    我在尝试在单个 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”

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2018-12-31
      • 1970-01-01
      • 2021-11-07
      • 2020-02-26
      • 1970-01-01
      • 2015-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多