首页 > 解决方案 > 如何将随机颜色应用于每个字母而不是单词?

问题描述

结果示例:

在此处输入图像描述

它适用于整个单词。如何对每个字母应用随机颜色?

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>

标签: javascriptarraysfunctionobjectdom-events

解决方案


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>


推荐阅读