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
423 views
in Technique[技术] by (71.8m points)

javascript - jQuery each letter in div element, random colour from array on hover

I'm trying to get each letter in a div element to change to a random colour from an array of colours. Then reset when the mouse moves off the div.

Here's what I've got so far. I think I'm pretty close, apart from the fact it doesn't actually work. This was built from a few different snippets on this site.

$(document).ready(function() {

    // COLOURS ARRAY
    var colours = Array("#ddd", "#333", "#999", "#bbb"), idx;

    $("DIV#header").hover(function(){

        $( $(this).text().split('')).each(function(index, character) {
            idx = Math.floor(Math.random() * colours.length);
            $(this).css("color", colours[idx]);
        });

    }, function() {
        $(this).css("color","#ddd");
    });

});

It doesn't produce any JS errors. The 2nd function of the hover seems to work but not the first. Any help would be gratefully received!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can only add styles to elements, wrap each character in a <span> and style the span.

#header {color: #ddd}?
<div id="header">Some text here</div>?
$(document).ready(function() {

    // COLOURS ARRAY
    var colours = Array("#ddd", "#333", "#999", "#bbb"), idx;

    $("#header").hover(function(){
        var header = $(this); 
        var characters = header.text().split('');
        header.empty();  
        var content = '';
        for(var i = 0; i < characters.length; i++) {
            idx = Math.floor(Math.random() * colours.length);
            content += '<span style="color:'+colours[idx]+'">' + characters[i] + '</span>'; 
        }
        header.append(content);
    }, function() {
        $(this).find('span').contents().unwrap();
    });

});

http://jsfiddle.net/vVNRF/


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

...