如何在 console.log 中显示彩虹消息

How to display rainbow message in console.log

你好,有一个用于彩虹化 console.log 输出的脚本。

当我尝试时,console.log 输出原始字符串,但如果我将此输出复制到另一个 console.log,他会以正确的颜色输出消息。

你知道为什么吗?

var input = document.getElementById('input');

input.addEventListener("blur", function() {
 var inputValue = input.value;
 var inputSplitted = inputValue.split("");
 
 let i = 0,
  inputLength = inputSplitted.length;
 var newLog ='"';
 var colors = "";
 for(i=0; i<inputLength; i++){
  // Chaque lettre est contenue dans inputSplitted[i]
  newLog += "%c"+inputSplitted[i];
  colors += ',"color: '+randomColor()+';"';
 }
 newLog +='"';
 var log = newLog+colors;
 console.log(log);
 console.log("%ch%ce%cl%cl%co%c %cw%co%cr%cl%cd","color: #144143;","color: #40C71F;","color: #5B7487;","color: #E3E226;","color: #6A8693;","color: #EC8802;","color: #9D44DE;","color: #1F1C4D;","color: #92812D;","color: #7A412C;","color: #73936F;");
});

function randomColor() {
 var letters = '0123456789ABCDEF';
 var color = '#';
 for (var i = 0; i < 6; i++ ) {
  color += letters[Math.floor(Math.random() * 16)];
 }
 return color;
}
<input type=text name=input id=input>

如评论中所述,浏览器将字符串作为字符串而不是参数来处理。

您必须声明一个数组并使用console.log.apply

看看:

var input = document.getElementById('input');

input.addEventListener("blur", function() {
 var inputValue = input.value;
 var inputSplitted = inputValue.split("");
 
 let i = 0,
  inputLength = inputSplitted.length;
 var newLog ='';
 var colors = "";
 for(i=0; i<inputLength; i++){
  // Chaque lettre est contenue dans inputSplitted[i]
  newLog += "%c"+inputSplitted[i];
  colors += '||color: '+randomColor()+';';
 }
 newLog +='';
 var log = newLog+colors;
 var arr = log.split('||');
 console.log.apply(console, arr);
 console.log("%ch%ce%cl%cl%co%c %cw%co%cr%cl%cd","color: #144143;","color: #40C71F;","color: #5B7487;","color: #E3E226;","color: #6A8693;","color: #EC8802;","color: #9D44DE;","color: #1F1C4D;","color: #92812D;","color: #7A412C;","color: #73936F;");
});



function randomColor() {
 var letters = '0123456789ABCDEF';
 var color = '#';
 for (var i = 0; i < 6; i++ ) {
  color += letters[Math.floor(Math.random() * 16)];
 }
 return color;
}
<input type=text name=input id=input>

希望这段代码对您有所帮助。 :)