javascript - 如何将随机颜色应用于每个字母而不是单词?
问题描述
结果示例:
它适用于整个单词。如何对每个字母应用随机颜色?
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>
解决方案
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>
推荐阅读
- python - 缩小差异?
- javascript - 如何动态加载javascript文件避免缓存?
- algorithm - 如何在 Haskell 中通过矩阵实现最小成本路径
- python - 如何使 fsolve 函数在 for 循环中工作?
- python - 如果您不关心列名,有没有办法摆脱错误排序的“重复”?
- facebook - 如何在 Expo 管理的应用程序中成功实现 expo-facebook 的基本配置?
- python - ModuleNotFoundError:M1 Macbook pro 中没有名为“mysql”的模块
- c# - ValidationAttribute 在 Blazor 上部分工作或不工作?
- android - 如何限制 LazyColumn 中的项目数?
- c# - 升级到 .NET 6 时,Web 项目引发运行时异常