Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

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

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 straight away (once the page loads). Please help. I would also like to know if anyone knows how to just set different colors on each letter (set colors) with css or Javascript because when I tried to do it in that way, it wouldnt allow me call a function on the same div/id (i tried to arch the text). Thank you.

THIS IS MY CODE

var colours = ["#000000", "#FF0000", "#990066", "#FF9966", "#996666", "#00FF00", "#CC9933"], 
    idx;

$("#arch").hover(function(){
    var div = $(this); 
    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);
    }

}, function() {
    $(this).find('span').css("color","#FF0000");
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
    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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...