2011-09-11 227 views
6

我使用jquery color生成一些随机的颜色。 Id像这些颜色在用户悬停在任何单选按钮标签上时显示。jquery随机颜色悬停

this site的例子,我想我可能会尝试:

spectrum(); 

function spectrum(){ 

var hue = ('lots of stuff here that generates random hue -- code on example webpage') 

$('label').hover(function() { 
    $(this).animate({ color: hue }, 10000) }); 

spectrum(); 

} 

我悬停选择不工作,一切都停留它的默认颜色。不管怎样,我显然都很笨拙,但我没有足够的经验去理解错误。有什么建议么?

+0

请张贴您的HTML和CSS。这里没有足够的代码来知道发生了什么问题。 – maxedison

+0

你需要什么?除了身体上的东西外,没有任何CSS。而html只是一堆输入标签。 – yoshi

回答

16

试试这个:

$(document).ready(function() { 
    $('label').hover(function() { 
     var hue = 'rgb(' 
      + (Math.floor(Math.random() * 256)) + ',' 
      + (Math.floor(Math.random() * 256)) + ',' 
      + (Math.floor(Math.random() * 256)) + ')'; 
     $(this).stop().animate({ color: hue }, 500); 
    },function() { 
     $(this).stop().animate({ color: '#000' }, 500); 
    }); 
}); 

也看到我jsfiddle

=== UPDATE ===

function startAnimation(o) { 
    var hue = 'rgb(' 
     + (Math.floor(Math.random() * 256)) + ',' 
     + (Math.floor(Math.random() * 256)) + ',' 
     + (Math.floor(Math.random() * 256)) + ')'; 
    $(o.currentTarget).animate({ color: hue }, 500, function() { 
     startAnimation(o); 
    }); 
} 

$(document).ready(function() { 
    $('label').hover(
     startAnimation, 
     function() { 
      $(this).stop().animate({ color: '#000' }, 500); 
     } 
    ); 
}); 

看到我更新jsfiddle

+0

所以这真的很接近我想要达到的目标。但不是每个悬停随机 - 我想要颜色随机随机变动,而徘徊。例如:如果颜色每秒都在变化,并且我悬停三秒钟,用户应该看到三种颜色....嗯,我不知道会发生什么,如果我拿出停止 – yoshi

+0

啊,好的。所以jQuery的颜色插件调用的功能,“转换”到另一种颜色。并保持不断变化的颜色,递归调用它自己。我把这个脚本放到那里,它工作!但仍然有问题,因为它需要大量的处理能力和网站摊位,每次我翱翔 – yoshi

+0

呀!你可以通过什么代码来做到吗? startAnimation向下传递“o”意味着什么? – yoshi

0

$('label').hover将为标签添加一个mouseover/mouseout事件。你无限的做到这一点,因为你一遍又一遍地调用频谱。 改为尝试此操作。

$('label').hover(function() { 
    (function anim() { 
     var hue = //hue stuff 
     $(this).animate({ 
      color: hue 
     }, 10000, function() { 
      anim(); 
     }); 
    })(); 
}, function() { 
    $(this).animate({ 
     color: //original color 
    }, 1000); 
});