2017-08-05 84 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