2017-08-05 85 views
-1

我正在编写一个应用程序,它接受用户输入并随机将颜色分配给文本中的每个字母。JavaScript:随机选择颜色作为基于输入的字母

HTML代码

<label id="text"> 
Retrieve data from selected text input among various text inputs with same 
name & id upon hitting Enter 
</label> 
<div> 
<input type="text" id="inputColors"> 
</div> 

<input id="Enter" type="button" value="Enter" /> 

的JavaScript

document.getElementById("Enter").onclick = function() { 
var colors = document.getElementById('inputColors').value; 
var colorslist = colors.split(/[;,]+/); 


$('#text').each(function() { 
    $(this).html($(this).text().split(' ').map(function(v) { 
    return '<span style="color:' + colorslist[Math.floor(Math.random() * 
colorslist.length)] + '">' + v + '</span>'; 
    }).join(' ')); 
}); 
} 

我能颜色的每个字,但希望它这样做对每个letter.I不想使用CSS。

+0

'.split( '')'代替'.split(”“)',很明显。 '.join'一样。 –

回答

1

您的代码当前在每个单词周围包围span,因为它的splits是空格字符上的字符串。

相反,您应该使用.split()将其拆分,它将返回所有字符(包括空格)的数组。

然后您需要使用.join()加入它们。

document.getElementById("Enter").onclick = function() { 
 
    var colors = document.getElementById('inputColors').value; 
 
    var colorslist = colors.split(/[;,]+/); 
 

 
    $('#text').each(function() { 
 
    $(this).html($(this).text().split('').map(function(v) { 
 
     return '<span style="color:' + colorslist[Math.floor(Math.random() * 
 
     colorslist.length)] + '">' + v + '</span>'; 
 
    }).join('')); 
 
    }); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="text"> 
 
    Retrieve data from selected text input among various text inputs with same name &amp; id upon hitting Enter 
 
</div> 
 
<input type="text" id="inputColors" value="red,yellow,blue,green,orange" /> 
 
<input id="Enter" type="button" value="Enter" />

+0

谢谢你的回答。我们有一种方法可以选择任意颜色,使得没有两个字母颜色相同? – Kevin

+0

您可以随机化地图以外的颜色。然后在地图内部迭代颜色,直到达到结束然后重置。他们不会是随机的。即它会重复rygbo,rygbo,如果你希望它是随机的(即ryrgbryo),你需要像地图一样在地图内部随意调用,但是如果它需要保留对前一个字符颜色的引用同样使用下一种颜色。 – Jamie