2011-09-11 219 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); 
});