如何为文本字段中的每个字母赋予不同的颜色? [英] How can I give different color for each letter in a text field?
问题描述
我有一个输入文字栏位,例如这,
名称:< input type =textname =textclass =text/>
我想对输入文本字段中的每个字母应用不同的颜色,如果用户输入
hai
字母h,a,i
相邻的字母应该有不同的颜色。让我选择红色和黄色。在jQuery中有没有办法,css?解决方案http://jsfiddle.net/DerekL/Y8ySy/
$(body)。prop(contentEditable,true).blur(function(){
var chars = $(this).text .innerHTML =;
$ .each(chars,function(){
$(< span>)。text(this).css({
color:# +(Math.random()* 16777215 | 0).toString(16)//只是一些随机颜色
})appendTo(body);
} );
您可以将事件实际设置为
keypress
如果用户只是用普通键盘进入。我使用blur
这里是因为keypress / keyup
会在用户使用IME输入文本时中断代码。 >
由于 Billy Mathews 提到,可能需要一个
input
,可以通过form
提交。这里是一个解决方案:< input type =hiddenid =hiddenEle
var chars = $(this).text()。split();
$(#hiddenEle)。val($(this).text());
this.innerHTML =;
只是为了有趣
这里是不会改变颜色的: http://jsfiddle.net/ DerekL / A7gL2 /
I have an input text field like this,
input { color: red }
Name: <input type="text" name="text" class="text" />
I want to apply different color for each letter in the input text field , If the user enters
hai
the each letterh,a,i
the adjacent letter should have different color .Let me choose red and yellow. Is there is any way for that in jQuery, css?解决方案http://jsfiddle.net/DerekL/Y8ySy/
$("body").prop("contentEditable", true).blur(function(){ var chars = $(this).text().split(""); this.innerHTML = ""; $.each(chars, function(){ $("<span>").text(this).css({ color: "#"+(Math.random()*16777215|0).toString(16) //just some random color }).appendTo("body"); }); });
You can actually set the event to
keypress
if the user is only going to enter with a normal keyboard. I usedblur
here becausekeypress/keyup
will break the code if the user is entering text with IME.As Billy Mathews mentioned, one might want to have an
input
that can be submitted byform
. Here is a solution:<input type="hidden" id="hiddenEle"> var chars = $(this).text().split(""); $("#hiddenEle").val($(this).text()); this.innerHTML = "";
Just for fun
Here is one that won't change color: http://jsfiddle.net/DerekL/A7gL2/
这篇关于如何为文本字段中的每个字母赋予不同的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!