最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I give different color for each letter in a text field? - Stack Overflow

programmeradmin2浏览0评论

I have an input text field like this,

input {
  color: red
}
Name:
<input type="text" name="text" class="text" />

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?

Share Improve this question edited Nov 27, 2015 at 9:43 Pranav C Balan asked Feb 9, 2014 at 3:36 Pranav C BalanPranav C Balan 115k25 gold badges171 silver badges195 bronze badges 6
  • It is not possible with only an <input>. – Derek 朕會功夫 Commented Feb 9, 2014 at 3:38
  • @Derek朕會功夫 : Any other way , something like content editable div – Pranav C Balan Commented Feb 9, 2014 at 3:39
  • text in input fields is not stylable to that level. You could use a contentEditable=true element, though. – Marc B Commented Feb 9, 2014 at 3:39
  • @PranavCBalan - I don't recommend programmatically wrapping characters in <span>s on key press because this will mess up IMEs. – Derek 朕會功夫 Commented Feb 9, 2014 at 3:43
  • @Derek朕會功夫 is there any other way color single letter without wrapping it using any tag – Pranav C Balan Commented Feb 9, 2014 at 3:46
 |  Show 1 more comment

3 Answers 3

Reset to default 15

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/

Why not make the input's font invisible and have some javascript that dynamically changes some text placed over the input as you type? Something like this:

<div>
    Name:<input type="text" name="text" class="text" />
    <div class="colors"></div>
</div>

JavaScript:

$(document).ready(function(){
    $('.text').keyup(function(){
        var output="";
        var letters = $(this).val().split("");
        letters.forEach(function(letter){
            var color = "#"+(Math.random()*16777215|0).toString(16);
            //Stolen from Derek's answer ;)
            output += '<span style="color: ' + color + ';">' + letter + '</span>';
          $('div.colors').html(output);
        });
    });
});

Then you just gotta position the div over the input; et voila! Not tested.. but I am making a jsFiddle now! http://jsfiddle.net/pranavcbalan/54EY4/6/

Update: Fixed the CTRL+A DEL problem. FIDDLE

var input = document.getElementById("input");
input.onkeydown = colorTheText;

function generateRandomColor() {
    var color = [];
    for (var i = 0; i < 3; i++) {
        color.push(Math.floor(Math.random()*250));
    }
    return color;
}

function rgbToHex(color) {
    var hex = [];
    for (var i = 0; i < 3; i++) {
        hex.push(color[i].toString(16));
        if (hex[i].length < 2) { hex[i] = "0" + hex[i]; }
    }
    return "#" + hex[0] + hex[1] + hex[2];
}

function setEndOfContenteditable(contentEditableElement) {
    var range,selection;
    if(document.createRange) {
        range = document.createRange();
        range.selectNodeContents(contentEditableElement);
        range.collapse(false);
        selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

var colors = [];
var inputLength = 0;
var ctrl = [];

function colorTheText(e) {
    if (e.keyCode == 8) {
        if (ctrl.indexOf(17) > -1 && ctrl.indexOf(65) > -1) {
            input.innerHTML = "";
            ctrl.length = 0;
        }
    } else {
        var text = input.innerText;
        if (text.length > inputLength) {
            inputLength++;
            colors.push(generateRandomColor());
        } else {
            inputLength--;
            colors.pop();
        }
        input.innerHTML = "";
        text = text.split("");
        for (var i = 0; i < text.length; i++) {
            if (colors[i]) {
                input.innerHTML += '<span style="color:' + rgbToHex(colors[i]) + '">' + text[i] + '</span>';
            }
        }
        setEndOfContenteditable(input);        
        if (e.keyCode == 17) {
            ctrl.length = 0;
            ctrl.push(17);
        }
        if (e.keyCode == 65) {
            if (ctrl[0] == 17 && ctrl.length == 1) {
                ctrl.push(65);
            }        
        }
    }
}


Even though the question is answered, I wanted to post my answer. Might come handy to future viewers.

In this one color change happens while typing, and it remembers the color order until the div is completely cleared.

And I know it's not perfect. Yet. Play with it.

FIDDLE

setEndOfContenteditable function taken from Nico Burn's answer.

var input = document.getElementById("input");
input.onkeydown = colorTheText;

function generateRandomColor() {
    var color = [];
    for (var i = 0; i < 3; i++) {
        color.push(Math.floor(Math.random()*250));
    }
    return color;
}

function rgbToHex(color) {
    var hex = [];
    for (var i = 0; i < 3; i++) {
        hex.push(color[i].toString(16));
        if (hex[i].length < 2) { hex[i] = "0" + hex[i]; }
    }
    return "#" + hex[0] + hex[1] + hex[2];
}

function setEndOfContenteditable(contentEditableElement) {
    var range,selection;
    if(document.createRange) {
        range = document.createRange();
        range.selectNodeContents(contentEditableElement);
        range.collapse(false);
        selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

var colors = [];
var inputLength = 0;

function colorTheText(e) {
    var text = input.innerText;
    if (text.length > inputLength) {
        inputLength++;
        colors.push(generateRandomColor());
    } else {
        inputLength--;
        colors.pop();
    }
    input.innerHTML = "";
    text = text.split("");
    for (var i = 0; i < text.length; i++) {
        if (colors[i]) {
            input.innerHTML += '<span style="color:' + rgbToHex(colors[i]) + '">' + text[i] + '</span>';
        }
    }
    setEndOfContenteditable(input);
}
发布评论

评论列表(0)

  1. 暂无评论