悬停时的jQuery随机链接颜色

时间:2011-10-26 23:30:59

标签: jquery css

下面的脚本完美无缺。但是,这并不是我想要实现的目标。我希望“悬停”它可以选择1种颜色并保持不变,而不是在悬停时循环显示每个链接的所有颜色。您可以在此处查看我不想要的效果示例http://www.morxmedia.com/

$(document).ready(function() {
  original = $('.menu-item a').css('color');
  $('.menu-item a').hover(function() { //mouseover
    var rand = Math.floor(Math.random() * 4);
 if(rand == 0){var col = '#EAD325';}
 else if(rand == 1){var col = '#FE902F';}
 else if(rand == 2){var col = '#82BE38';}
 else if(rand == 3){var col = '#217AFC';}
 else{var col = '#888888';}

    $(this).animate({'color': col,});
  },function() { //mouseout
    $(this).animate({
      'color': original,
    });
  });
});

2 个答案:

答案 0 :(得分:2)

为每个链接生成随机颜色,将其保存到数组中。在悬停时,它会检查它应该是什么颜色,并为其设置动画。

参见工作示例:http://jsfiddle.net/fRqj2/

$(document).ready(function() {

    var assignedColors = new Array();

    $('.menu-item a').each(function(i) {
        var rand = Math.floor(Math.random() * 4);
        if (rand == 0) {
            var col = '#EAD325';
        }
        else if (rand == 1) {
            var col = '#FE902F';
        }
        else if (rand == 2) {
            var col = '#82BE38';
        }
        else if (rand == 3) {
            var col = '#217AFC';
        }
        else {
            var col = '#888888';
        }
        assignedColors[i] = col;
    });

    original = $('.menu-item a').css('color');
    $('.menu-item a').hover(function() { //mouseover
        index = $(this).parent().prevAll().length;
        $(this).animate({
            'color': assignedColors[index]
        });
    }, function() { //mouseout
        $(this).animate({
            'color': original,
        });
    });
});

答案 1 :(得分:0)

您可以使用.data()标记元素的颜色。像这样:

  ...
  col = $(this).data("hoverColor"); // Tries to load the color for the element
  if (! col ) {
    col = getRandomColor();
    $(this).data("hoverColor", col ); // Saves the color for the element
  }
  ...
相关问题