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

前端 未结 4 1076
星月不相逢
星月不相逢 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: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';
        }
        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/

提交回复
热议问题