How to make each letter in text a different random color in Javascript

前端 未结 2 1646
孤独总比滥情好
孤独总比滥情好 2020-12-21 21:55

I am trying to make every letter in a small line of text a different random color. I can only seem to make it do this when I use .hover, but I want it to do the action strai

相关标签:
2条回答
  • 2020-12-21 22:06

    Try (untested):

    $(document).ready(function(){
        var div = $('#arch'); 
        var chars = div.text().split('');
        div.html('');     
        for(var i=0; i<chars.length; i++) {
            idx = Math.floor(Math.random() * colours.length);
            var span = $('<span>' + chars[i] + '</span>').css("color", colours[idx])
            div.append(span);
        }
    }
    

    Basically, you need to wait for the DOM to load so that there's a div to find when you call $('#arch')!

    I'm not sure what you mean by "tried to arch the text".

    0 讨论(0)
  • 2020-12-21 22:25
        var colours = ["#000000", "#FF0000", "#990066", "#FF9966", "#996666", "#00FF00", "#CC9933"], 
        idx;
    
    $(function() {
        var div = $('#arch'); 
        var chars = div.text().split('');
        div.html('');     
        for(var i=0; i<chars.length; i++) {
            idx = Math.floor(Math.random() * colours.length);
            var span = $('<span>' + chars[i] + '</span>').css("color", colours[idx]);
            div.append(span);
        }
    });
    

    Works for me. jsFiddle

    You have to make sure the DOM is loaded before doing any jQuery stuff on it.

    http://learn.jquery.com/using-jquery-core/document-ready/

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