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

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

I have an input text field like this,



        
相关标签:
3条回答
  • 2020-12-06 19:07

    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 讨论(0)
  • 2020-12-06 19:14

    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/

    0 讨论(0)
  • 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(){
            $("<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/

    0 讨论(0)
提交回复
热议问题