How do I alternate letter colors on a webpage using javascript?

前端 未结 4 1034
星月不相逢
星月不相逢 2021-01-24 15:05

I\'m trying to alternate the colors of every letter in a specific div on my webpage using javascript.

I found this script on a forum that alternates the color of the wor

相关标签:
4条回答
  • 2021-01-24 15:17

    Problem #1: No need to define var HTML outside of the scope of the function. No need to define it at all, really.

    Problem #2: You are splitting by a space ' ' which would alternate words, not letters.

    Problem #3: You're not stripping out existing tags, so if you select a color pair once, then select another, you'll be putting html into your text.

    Problem #4: If you select 'select colors', it will throw an error trying to get colorpair[1] which won't exist

    Problem #5: You're adding spaces at the end of each letter, which will break further attempts, as each alternating character will be a space. You'll only see one color! :P

    Fixed code:

    function alternate(colorpair) {
        if(colorpair.indexOf('|') == -1) return;
        var el = document.getElementById('alternator');
        colorpair = colorpair.split('|');
        var letters = el.innerHTML.replace(/^\s*|\s*$/g,''). /*strip leading/trailing spaces*/
                      replace(/<[^>]*>/g,''). /*strip existing html tags */
                      split(''), 
            output = '';
        for (var w = 0, l = letters.length; w < l; w++) {
            output += '<span style="color:' + ((w % 2) ? colorpair[0] : colorpair[1]) + ';">' + letters[w] + '</span>';
        }
        el.innerHTML = output;
    }
    

    JSFiddle Demo: http://jsfiddle.net/xpZqs/

    0 讨论(0)
  • 2021-01-24 15:18

    Here is one way to do this, just replace your JavaScript code with the following (and remove the form from your HTML since you just want this to happen on page load):

    var HTML = '';
    
    function alternate(colorpair) {
        var el = document.getElementById('alternator');
        if (!HTML) HTML = el.innerHTML;
        var text = HTML.match(/\S\s*(?=\S)/g), output = '';
        for (var w=0; w<text.length; w++) {
            output += '<span style="color:' + ((w%2) ? colorpair[0] : colorpair[1]);
            output += ';">' + text[w] + '</span>';
        }
        console.log(output);
        el.innerHTML = output;
    }
    alternate(['green', 'purple']);
    

    Note that with this method you will also skip spaces so the coloring looks a little better. Here is what the end result looks like:

    enter image description here

    Example: http://jsfiddle.net/pzeCQ/

    0 讨论(0)
  • 2021-01-24 15:27

    Replace this:

    var text = HTML.split(' '), output = '';
    for (var w=0; w<text.length; w++) {
        output += '<span style="color:' + ((w%2) ? colorpair[0] : colorpair[1]);
        output += ';">' + text[w] + '</span> ';
    }
    

    With this:

    for (var c=0; c<HTML.length; c++) {
        output += '<span style="color:' + ((c%2) ? colorpair[0] : colorpair[1]);
        output += ';">' + HTML.CharAt(c) + '</span> ';
    }
    

    The output's going to be pretty verbose. If you want to skip spaces, you'll need to add a little logic for that.

    0 讨论(0)
  • 2021-01-24 15:36

    I've got a simple demo:

    This assumes that the text is already on the page, only affects text (using innerText), and replaces the text inside the div with the required html

    function alternateColours() {
        var div = document.getElementById("alternator");
        var message = div.innerText;
        html = "";
        var colors = new Array("#ff0000","#00ff00","#0000ff"); // red, green, blue
        for (var i = 0; i < message.length; i++)
            html += "<span style=\"color:" + colors[(i % colors.length)] + ";\">" + message[i] + "    </span>";
        div.innerHTML = html;
    }
    alternateColours();
    

    I would recommend the use of jQuery to attach the function to the page load, much cleaner that having to do it yourself.

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