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

前端 未结 4 1504
我寻月下人不归
我寻月下人不归 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:25

    A string is not an element and you cannot add a CSS property to it. You can put your letters in span elements and then style them, try this:

    $(document).ready(function() {
    
        // COLOURS ARRAY
        var colours = Array("#ffffd", "#333", "#999", "#bbb"), idx;
    
        $('DIV#header').hover(function(){
    
            $('span', this).each(function(index, character) {
                idx = Math.floor(Math.random() * colours.length);
                $(this).css("color", colours[idx]);
            });
    
        }, function() {
            $('span',this).css("color","#ffffd");
        });
    
    }); 
    

    http://jsfiddle.net/BC5jt/

提交回复
热议问题