如何为文本字段中的每个字母赋予不同的颜色? [英] How can I give different color for each letter in a text field?

查看:220
本文介绍了如何为文本字段中的每个字母赋予不同的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入文字栏位,例如



 

 名称:< 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 letter h,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 used blur here because keypress/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 by form. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆