2011-10-14 50 views
0

我正在研究css,當鼠標懸停在圖像上時,它變得更大。例如用JavaScript過渡到懸停狀態

#image-div img { width:100px; height:100px;} 
#image-div:hover img { width:200px; height:200px;} 

現在我想讓它變得有點動畫。就像它應該慢慢地放大一樣,並且在小鼠外面,它應該慢慢地縮小。請幫忙。

注:我不是很熟悉javascript。

回答

2

這些動畫通常是用Javascript完成的。而不是手工編寫Javascript,可能更容易使用包含「.animate()」方法的jQuery庫。該動畫的方法要求你放棄目標的CSS屬性作爲參數,就像這樣:

(因爲你寫你不熟悉JavaScript,我已經包括一切你需要包括jQuery庫)

<script src="http://www.google.com/jsapi" type="text/javascript"></script> 

<script type="text/javascript">google.load("jquery", "1.6.4");</script> 

<script type="text/javascript"> 

    $(document).ready(function(){ 

     $("#image-div img").live({mouseenter:myfin, 
       mouseleave:myfout}); 

    }); 
    function myfin() { 
    $(this).animate({height: 200, width: 200},1000); //1000 = 1 second animation 
} 
function myfout() { 
    $(this).animate({height: '', width: ''},1000); //1000 = 1 second animation 
    //setting the height and width to '' will clear the inserted style, leaving you with your original style 
} 
</script> 

然後,你應該只需要在CSS中設置高度和寬度爲100px,並刪除#image-div:hover定義。

如果您想在CSS文件中使用類定義進行動畫製作,您可以使用jQuery插件進行動畫製作。請參見上的幫助以下問題:

jQuery.animate() with css class only, without explicit styles

+0

這就是完美的兄弟。精彩。非常感謝。標記你的答案。 – themajiks

+0

還有一個問題。如果你將鼠標懸停並快速滑出10次,它將完成10次循環。唯一的問題。 – themajiks

+0

試試這個: $(「#image-div img:not(:animated)」)。live({mouseenter:myfin, mouseleave:myfout}); –

0

查看.animate()方法並將其與.hover()配對。這將允許您在鼠標懸停在特定元素上時應用特定的過渡,在此情況下,根據需要進行縮放。

2

如果沒有需要支持舊的瀏覽器,你可以使用CSS3過渡屬性。它不需要任何JavaScript,可用於Safari,Firefox和Opera。 http://www.w3schools.com/css3/css3_transitions.asp

#image-div img { 
    width:100px; 
    height:100px; 
    transition:all 1s ease-in-out 
    -moz-transition:all 1s ease-in-out; 
    -webkit-transition:all 1s ease-in-out; 
    -o-transition:all 1s ease-in-out; 
} 
#image-div:hover img { 
    width:200px; 
    height:200px; 
} 
+0

是的。我已經這樣做了,但不知何故,我的客戶端也需要動畫才能在較舊的瀏覽器中工作。 – themajiks