Colors in JavaScript console

前端 未结 27 2187
说谎
说谎 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:02

    Check this out:

    Animation in console, plus CSS

    (function() {
      var frame = 0;
      var frames = [
        "This",
        "is",
        "SPARTA!",
        " ",
        "SPARTA!",
        " ",
        "SPARTA!",
        " ",
        "SPARTA!",
        " ",
        "SPARTA!",
        " ",
        "SPARTA!"
      ];
      var showNext = () => {
        console.clear();
        console.log(
          `%c `,
          "background: red; color: white; font-size: 15px; padding: 3px 41%;"
        );
        console.log(
          `%c ${frames[frame]}`,
          "background: red; color: white; font-size: 25px; padding: 3px 40%;"
        );
        console.log(
          `%c `,
          "background: red; color: white; font-size: 15px; padding: 3px 41%;"
        );
        setTimeout(
          showNext,
          frames[frame] === "SPARTA!" || frames[frame] === " " ? 100 : 1500
        );
        // next frame and loop
        frame++;
        if (frame >= frames.length) {
          frame = 0;
        }
      };
      showNext();
    })();
    

    https://jsfiddle.net/a8y3jhfL/

    you can paste ASCII in each frame to watch an ASCII animation

    0 讨论(0)
  • 2020-11-22 12:04

    In Chrome & Firefox (+31) you can add CSS in console.log messages:

    console.log('%c Oh my heavens! ', 'background: #222; color: #bada55');

    Console color example in Chrome

    The same can be applied for adding multiple CSS to same command.

    References

    • MDN: Styling console output
    • Chrome: Console API Reference
    0 讨论(0)
  • 2020-11-22 12:04

    const coloring = fn => ({ background, color = 'white' }) => (...text) => fn(`%c${text.join('')}`, `color:${color};background:${background}`);
    const colors = {
      primary: '#007bff',
      success: '#28a745',
      warning: '#ffc107',
      danger: '#dc3545',
      info: '#17a2b8',
    };
    const dir = (key = '', value = {}) => {
      logs.primary(`++++++++++++start:${key}++++++++++++++`);
      console.dir(value);
      logs.primary(`++++++++++++end:${key}++++++++++++++`);
    };
    const logs = Object.keys(colors)
      .reduce((prev, curr) => ({ ...prev, [curr]: coloring(console.log)({ background: colors[curr] }) }), { dir });
      
      logs.success('hello succes');
      logs.warning('hello fail');

    0 讨论(0)
  • 2020-11-22 12:06

    If you want to color your terminal console, then you can use npm package chalk

    npm i chalk
    

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-11-22 12:07

    To chain CSS3 styles which spans across multiple lines, you can do like this,

    var styles = [
        'background: linear-gradient(#D33106, #571402)'
        , 'border: 1px solid #3E0E02'
        , 'color: white'
        , 'display: block'
        , 'text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)'
        , 'box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset'
        , 'line-height: 40px'
        , 'text-align: center'
        , 'font-weight: bold'
    ].join(';');
    
    console.log('%c a spicy log message ?', styles);
    

    Result

    Find more :- https://coderwall.com/p/fskzdw/colorful-console-log

    Cheers.

    0 讨论(0)
提交回复
热议问题