键入时将文字更改为不同的颜色

change word text different color when typing

本文关键字:颜色 文字      更新时间:2023-09-26

我在一个文本框中键入匹配的数据,然后更改文本的颜色,第二次键入,然后更改其他颜色,然后再次键入,然后再次更改颜色。

使用on()input事件处理程序绑定到文本字段,内部事件处理程序从数组更改颜色

var color = ['red', 'yellow', 'red', 'blue', 'brown'];
var i = 0;
$('#text').on('input',function() {
  $(this).css('color', color[i]);
  i = (i + 1) % color.length;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="text"/>


或者使用Math.random()生成随机颜色代码

var color = ['red', 'yellow', 'red', 'blue', 'brown'];
$('#text').on('input', function() {
  $(this).css('color', "#" + (Math.random() * 16777215 | 0).toString(16));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="text" />