2012-11-23 160 views
-1

我有這一段代碼,我生成一個隨機的顏色,並將其轉換爲十六進制設置,然後我想將其設置爲.ribbon a:hover跨度類的backgroundColorjQuery的隨機顏色 - 懸停不工作

<script type="text/javascript"> 
$(function() { 

    var randomColor = Math.floor(Math.random()*16777215).toString(16); 
    alert(randomColor); 
    $(".ribbon a:hover span").css({ 

     backgroundColor: '#' + randomColor 

    }); 



}); 
</script> 

這裏是我的CSS:

.ribbon a:hover span { 
    background: /*<?php printf("#%06X\n", mt_rand(0, 0xFFFFFF)); ?>*/ #FFF; 
    margin-top:0; 
} 

,它甚至沒有提醒我的randomColor變量...我已經把這個腳本</body>標記之前...

+1

您確定要導入jQuery嗎?你在控制檯中有錯誤嗎? –

+0

@mookamafoob只要dom準備就緒,jQuery就會調用這個函數。 –

+0

@mookamafoob呃,嗯? jQuery的? – Madbreaks

回答

1

首先更換

<script src="http://www.google.com/jsapi"></script> 
<!-- load JQuery and UI from Google (need to use UI to animate colors) --> 
<script type="text/javascript"> google.load("jqueryui", "1.5.2"); </script> 

,你必須加載jQuery的 - 你所提供的代碼只加載jQuery UI的。

<script src="http://www.google.com/jsapi"></script> 
<!-- load JQuery and UI from Google (need to use UI to animate colors) --> 
<script type="text/javascript"> 
    google.load("jquery", "1.5.2"); 
    google.load("jqueryui", "1.5.2"); 
</script> 

其次,你可以不是一個函數綁定到:hover選擇一樣,你需要使用jQuery的功能.hover

<script type="text/javascript"> 
$(function() { 


    $(".ribbon a").hover(function() { 
     // change to random color on mouseover 
     var randomColor = Math.floor(Math.random()*16777215).toString(16); 
     alert(randomColor); 
     $(this).find('span').css({ 
      backgroundColor: '#' + randomColor 
     }); 
    }, function() { 
     // change back to original color on mouseout 
     $(this).find('span').css({ 
      backgroundColor: '#FFF' 
     }); 
    }); 
}); 
</script> 
+2

注意op說''alert'永遠不會發生。除了你在這裏的建議之外,他正在處理一些事情。 – Madbreaks

+0

編輯我的帖子,包括加載jquery – freejosh

+0

是的!這完全是我想要的!你是我的英雄!非常感謝!謝謝!!! – moritzg

4

jQu eryUI不包含jQuery:你仍然需要加載它(之前)。

所以,你應該用

<script src="http://www.google.com/jsapi"></script> <!-- load JQuery and UI from Google (need to use UI to animate colors) --> 
<script type="text/javascript"> 
google.load("jquery", "1.5.2"); 
google.load("jqueryui", "1.5.2"); 
</script> 
+2

爲什麼downvote?請看https://developers.google.com/loader/ –

+1

另外,你可能需要一個比1.5.2更新的jQuery版本。另外,一旦OP修復了他的jQuery加載問題,仍然有胡扯(對於jQuery)選擇器'$(「。ribbon a:hover span」)''。 – thirtydot

+0

你好,進口工作!但是現在我該如何設置班級的背景顏色? – moritzg

0

要麼你不進口的jQuery,或者您有代碼中其他地方的JS錯誤導致整個腳本作爲整體被破壞。首先,檢查您的控制檯是否有任何錯誤。如果沒有顯示任何內容,請嘗試將腳本更改爲:

<script type="text/javascript"> 
    $(function(){ 
     alert('jQuery is alive!'); 
    }); 
</script>