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

前端 未结 4 1047
星月不相逢
星月不相逢 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: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 += "" + message[i] + "    ";
        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.

提交回复
热议问题