Change console.log message color

后端 未结 7 704
我寻月下人不归
我寻月下人不归 2021-01-31 03:12

Is there a way to do something like:

console.log(\"hello world\", \'#FF0000\')

in Chrome/Safari or Firefox ?

相关标签:
7条回答
  • 2021-01-31 03:40

    Inspired by Jaden's answer. Made a little log function.

    function log(msg, color) {
    
      var css = "",
      paint = { // default colors
        clr: "#212121",
        bgc: "#b0bec5"
      },
      colors = {
        error: {clr:"#ffebee", bgc:"#c62828"}, // red
        success: {clr: "#e8f5e9", bgc: "#2e7d32"}, // green
        warning: {clr: "#fff3e0", bgc: "#f4511e"}, // orange
        info: {clr: "#ede7f6", bgc: "#651fff"} // purple
      };
    
      // overriting default colors if color given
      if (colors.hasOwnProperty(color)){ paint.clr = colors[color].clr; paint.bgc = colors[color].bgc; }
      css = "color:" + paint.clr + ";font-weight:bold; background-color: " + paint.bgc + "; padding: 3px 6px; border-radius: 2px;";
    
      console.log("%c"+msg, css);
    }
    

    Test

    log("Default");
    log("Error", "error");
    log("Success", "success");
    log("Warning", "warning");
    log("Info", "info");
    

    What it looks like

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