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

前端 未结 4 1033
星月不相逢
星月不相逢 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 += '' + letters[w] + '';
        }
        el.innerHTML = output;
    }
    

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

提交回复
热议问题