2011-10-26 29 views
2

下面的腳本完美地工作。但是,這並不是我想要達到的目標。我希望'懸停'它可以選擇1種顏色並保持不變,而不是通過懸停時每個鏈接的所有顏色循環。你可以看到效果的例子,我不想在這裏http://www.morxmedia.com/jQuery懸停時的隨機鏈接顏色

$(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

爲每個鏈接生成隨機顏色,並將其保存到數組中。懸停時,它會檢查它應該是什麼顏色,併爲其設置動畫。

見工作示例: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, 
     }); 
    }); 
}); 
+0

謝謝!但是,它似乎沒有隨機化jsfiddle上的顏色。 – Stephen

+0

它在這裏工作。我們同意,它應該只更新頁面重新加載顏色的權利?試試這個:http://jsfiddle.net/fRqj2/1/ - 更新它應該發佈隨機顏色的警報:) –

+0

嗯,以及我只是測試它的生活,這可能與我使用的其他代碼的問題..它似乎有一個隨機的顏色,並褪成另一種隨機顏色,你可以看到這裏:http://morxmedia.com/我使用你的代碼 – Stephen

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 
    } 
    ... 
+0

我不是非常有效的JavaScript。我最好的HTML/CSS和圖形設計哈哈。你能否以我能用我列出的顏色複製和粘貼的方式重寫?我真的很感激它。 :) – Stephen