Colors in JavaScript console

前端 未结 27 2161
说谎
说谎 2020-11-22 11:42

Can Chrome\'s built-in JavaScript console display colors?

I want errors in red, warnings in orange and console.log\'s in green. Is that possible?

27条回答
  •  隐瞒了意图╮
    2020-11-22 12:06

    // log in color 
    // consolelog({"color":"red","background-color":"blue"},1,2,3)
    
    // consolelog({"color":"red"},1,2,3)
    // consolelog(1,2,3)
    function consolelog()
    {
        var style=Array.prototype.slice.call(arguments,0,1)||["black"];
        var vars=(Array.prototype.slice.call(arguments,1)||[""])
        var message=vars.join(" ")
        var colors = 
            {
                warn:
                    {
                        "background-color"  :"yellow",
                        "color"             :"red"
                    },
                error:
                    {
                        "background-color"  :"red",
                        "color"             :"yellow"
                    },
                highlight:
                    {
                        "background-color"  :"yellow",
                        "color"             :"black"
                    },
                success : "green", 
                info    : "dodgerblue"  
    
            }
        var givenstyle=style[0];
        var colortouse= colors[givenstyle] || givenstyle;
        if(typeof colortouse=="object")
        {
            colortouse= printobject(colortouse)
        }
        if(colortouse)
        {
            colortouse=(colortouse.match(/\W/)?"":"color:")+colortouse;
        }
        function printobject(o){
            var str='';
    
            for(var p in o){
                if(typeof o[p] == 'string'){
                    str+= p + ': ' + o[p]+'; \n';
                }else{
                str+= p + ': { \n' + print(o[p]) + '}';
                }
            }
    
            return str;
        }
        if(colortouse)
        {
            console.log("%c" + message, colortouse);
        }
        else
        {
            console.log.apply(null,vars);
        }
    }
    console.logc=consolelog;
    

提交回复
热议问题