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

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

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

    #header {color: #ffffd}​
    
    $(document).ready(function() {
    
        // COLOURS ARRAY
        var colours = Array("#ffffd", "#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 += '' + characters[i] + ''; 
            }
            header.append(content);
        }, function() {
            $(this).find('span').contents().unwrap();
        });
    
    });
    

    http://jsfiddle.net/vVNRF/

提交回复
热议问题