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

落花浮王杯 提交于 2019-11-27 22:41:01

问题


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!


回答1:


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("#ddd", "#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","#ddd");
    });

}); 

http://jsfiddle.net/BC5jt/




回答2:


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/




回答3:


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("#ddd", "#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', '#ddd');
});

// 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/




回答4:


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 = ["#ddd", "#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","#ddd");
    });

});​

http://jsfiddle.net/Mv4pw/



来源:https://stackoverflow.com/questions/12555995/jquery-each-letter-in-div-element-random-colour-from-array-on-hover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!