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

前端 未结 4 1506
我寻月下人不归
我寻月下人不归 2020-12-17 03:20

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\'v

4条回答
  •  误落风尘
    2020-12-17 03:31

    Well, it's exactly what Musa said, you can't apply styles to text nodes, you need a element around each character. Here is some example code that adds the spans dynamically:

    $(document).ready(function() {
    
        // COLOURS ARRAY
        var colours = ["#ffffd", "#333", "#999", "#bbb"], 
            idx;
    
        $("DIV#header").hover(function(){
            var div = $(this); 
            var chars = div.text().split('');
            div.html('');     
            for(var i=0; i' + chars[i] + '').css("color", colours[idx])
                div.append(span);
            }
    
        }, function() {
            $(this).find('span').css("color","#ffffd");
        });
    
    });​
    

    http://jsfiddle.net/Mv4pw/

提交回复
热议问题