How can I give different color for each letter in a text field?

前端 未结 3 1034
余生分开走
余生分开走 2020-12-06 18:59

I have an input text field like this,



        
3条回答
  •  甜味超标
    2020-12-06 19:19

    http://jsfiddle.net/DerekL/Y8ySy/

    $("body").prop("contentEditable", true).blur(function(){
        var chars = $(this).text().split("");
        this.innerHTML = "";
        $.each(chars, function(){
            $("").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:

    
    
    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/

提交回复
热议问题