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

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

    0 讨论(0)
  • 2020-12-17 03:31

    Well, it's exactly what Musa said, you can't apply styles to text nodes, you need a <span> 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.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","#ffffd");
        });
    
    });​
    

    http://jsfiddle.net/Mv4pw/

    0 讨论(0)
  • 2020-12-17 03:32

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

    #header {color: #ffffd}​
    
    <div id="header">Some text here</div>​
    
    $(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 += '<span style="color:'+colours[idx]+'">' + characters[i] + '</span>'; 
            }
            header.append(content);
        }, function() {
            $(this).find('span').contents().unwrap();
        });
    
    });
    

    http://jsfiddle.net/vVNRF/

    0 讨论(0)
  • 2020-12-17 03:46

    As others have pointed out, you can only style something that is an element, so you need to wrap each letter in it's own element. Here is an example way to do this. It works recursively too, so this will work with text that contains other elements, like <b>, <a>, and such. The other examples below assume that the div will have only text and no other HTML tags inside.

    var colours = Array("#ffffd", "#333", "#999", "#bbb");
    
    $('#header').hover(function(){
        wrapLetters(this);
        $('.random-color', this).css('color', function(){
            var idx = Math.floor(Math.random() * colours.length);
            return colours[idx];
        });
    }, function(){
        $('.random-color', this).css('color', '#ffffd');
    });
    
    // Wrap every letter in a <span> with .random-color class.
    function wrapLetters(el){
        if ($(el).hasClass('random-color')) return;
    
        // Go through children, need to make it an array because we modify
        // childNodes inside the loop and things get confused by that.
        $.each($.makeArray(el.childNodes), function(i, node){
            // Recursively wrap things that aren't text.
            if (node.nodeType !== Node.TEXT_NODE) return wrapLetters(node);
    
            // Create new spans for every letter.
            $.each(node.data, function(j, letter){
                var span = $('<span class="random-color">').text(letter);
                node.parentElement.insertBefore(span[0], node);
            });
    
            // Remove old non-wrapped text.
            node.parentElement.removeChild(node);
        });
    }
    

    Fiddle: http://jsfiddle.net/aWE9U/2/

    0 讨论(0)
提交回复
热议问题