结果示例:
它适用于整个单词。如何对每个字母应用随机颜色?
let input = document.querySelector('.input');
let output = document.querySelector('.output');
let colors = ['tomato', 'deeppink', 'skyblue', 'dodgerblue', 'violet', 'darkslateblue', 'green', 'crimson']
function colorNames(e) {
let inputVal = document.querySelector('input').value;
output.innerHTML = inputVal; // print out
let randomColors = Math.floor((Math.random() * colors.length + 1)); // random color names
if (output.innerHTML) {
output.style.color = colors[randomColors];
}
}
input.addEventListener('input', colorNames);
<input type="text" class="input" placeholder="Type your name">
<div class="output">
<!-- typed value will be printed here -->
</div>
答案 0 :(得分:0)
var colors = ['tomato', 'deeppink', 'skyblue', 'dodgerblue', 'violet', 'darkslateblue', 'green', 'crimson']
var output = document.querySelector(".output");
var input = document.querySelector(".input");
input.addEventListener("keyup",outputText);
function getRandomColor() {
return colors[Math.floor(Math.random() * colors.length)];
}
function outputText() {
var val = input.value;
var res = [];
for(var i = 0; i < val.length; i++) {
res[i] = val[i];
res[i] = '<span style="color:' + getRandomColor() + ';">' + res[i] + '</span>'
}
output.innerHTML = "";
for(var i = 0; i < val.length; i++) {
output.innerHTML += res[i]
}
}
<input type="text" class="input" placeholder="Type your name">
<div class="output">
</div>
答案 1 :(得分:0)
要为每个字母设置随机颜色,您必须将每个字母转换为单独的元素。
您可以使用空字符串public static int charRunCount(String str, char c) {
char last = 0;
int counter = 0;
for (int i = 0; i < str.length(); i++) {
// whenever a run starts.
if (last != c && str.charAt(i) == c)
counter++;
last = str.charAt(i);
}
return counter;
}
替换所有字符。然后使用split()
用map()
元素包裹每个字母,以便您可以在每个字母上应用样式(随机颜色)。生成数组后,必须先span
将它们分配给输出元素的join()
属性。
尝试以下方式:
innerHTML
let input = document.querySelector('.input');
let output = document.querySelector('.output');
let colors = ['tomato', 'deeppink', 'skyblue', 'dodgerblue', 'violet', 'darkslateblue', 'green', 'crimson']
function colorNames(e) {
let inputVal = document.querySelector('input').value.split('');
inputVal = inputVal.map(l => {
let randomColors = Math.floor((Math.random() * colors.length + 1));
l = '<span style=color:'+colors[randomColors]+'>' + l +'</span>';
return l;
});
output.innerHTML = inputVal.join(''); // print out
}
input.addEventListener('input', colorNames);