你有一个用于rainbowtizing 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;
}
&#13;
<input type=text name=input id=input>
&#13;
答案 0 :(得分:1)
正如在评论中所说,浏览器将字符串处理为字符串而不是参数。
您必须声明一个数组并使用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>
希望此代码能为您提供帮助。 :)