简体   繁体   English

jQuery div元素中的每个字母,悬停时来自数组的随机颜色

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

I'm trying to get each letter in a div element to change to a random colour from an array of colours. 我正在尝试使div元素中的每个字母从颜色数组更改为随机颜色。 Then reset when the mouse moves off the div. 然后在鼠标移离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. 它不会产生任何JS错误。 The 2nd function of the hover seems to work but not the first. 悬停的第二个功能似乎起作用,但第一个没有起作用。 Any help would be gratefully received! 任何帮助将不胜感激!

You can only add styles to elements, wrap each character in a <span> and style the span. 您只能将样式添加到元素,将每个字符包装在<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/ http://jsfiddle.net/vVNRF/

Well, it's exactly what Musa said, you can't apply styles to text nodes, you need a <span> element around each character. 好吧,这正是Musa所说的,您不能将样式应用于文本节点,每个字符周围需要一个<span>元素。 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/ http://jsfiddle.net/Mv4pw/

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. 它也可以递归工作,因此它可以与包含其他元素(例如<b><a>等)的文本一起使用。 The other examples below assume that the div will have only text and no other HTML tags inside. 下面的其他示例假定div内仅包含文本,而没有其他HTML标记。

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/ 小提琴: http : //jsfiddle.net/aWE9U/2/

A string is not an element and you cannot add a CSS property to it. 字符串不是元素,您不能向其添加CSS属性。 You can put your letters in span elements and then style them, try this: 您可以将字母放在span元素中,然后设置其样式,请尝试以下操作:

$(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/ http://jsfiddle.net/BC5jt/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM