2011-10-08 55 views
21

我已經創建了我申請到一個元素的:hover狀態的簡單動畫反彈:css3動畫:懸停;迫使整個動畫

@keyframes bounce { 
    0% { 
     top: 0; 
     animation-timing-function: ease-out; 
    } 
    17% { 
     top: 15px; 
     animation-timing-function: ease-in; 
    } 
    34% { 
     top: 0; 
     animation-timing-function: ease-out; 
    } 
    51% { 
     top: 8px; 
     animation-timing-function: ease-in; 
    } 
    68% { 
     top: 0px; 
     animation-timing-function: ease-out; 
    } 
    85% { 
     top: 3px; 
     animation-timing-function: ease-in; 
    } 
    100% { 
     top: 0; 
    } 
} 

.box:hover { 
    animation: bounce 1s; 
} 

動畫正常工作,不同之處在於,當你從元素中刪除光標它突然停止。無論如何強迫它繼續設定的迭代次數,即使鼠標已經退出?基本上我在這裏尋找的是由:hover狀態觸發的動畫。我是不是尋找javascript解決方案。我還沒有看到在規範中做到這一點,但也許有一個我在這裏錯過的明顯解決方案?

這裏玩小提琴:http://jsfiddle.net/dwick/vFtfF/

回答

21

恐怕只有這樣,才能解決這個問題是一個JavaScript代碼,你必須添加動畫作爲一個類,然後將其刪除動畫結束時。

$(".box").bind("webkitAnimationEnd mozAnimationEnd animationend", function(){ 
    $(this).removeClass("animated") 
}) 

$(".box").hover(function(){ 
    $(this).addClass("animated");   
}) 

http://jsfiddle.net/u7vXT/

+0

希望能夠避開javascript,但我想這是唯一的方法。 –

+0

瀏覽器不可知的事件名稱應該全部小寫:animationend – jackocnr

+0

https://developer.mozilla.org/en-US/docs/Web/Events/animationend –

2

一個簡單的技巧將做的工作:

-webkit-animation:swing 3600ms ease-in-out 6000s; 
-webkit-transform-origin:top; 

設置 '延遲' 與元件(未:懸停)上的高值。

來源:Stackoverflow - Robert McKee

0

CSS可能有助於在某些情況下,但不是全部,下面是將兩個懸停和懸停後動畫字符間距的代碼。

h1 
 
{ 
 
    -webkit-transition:all 0.3s ease; 
 
} 
 

 
h1:hover 
 
{ 
 
    -webkit-transition:all 0.3s ease; 
 
    letter-spacing:3px; 
 
}
<body> 
 
    <h1>Hello</h1> 
 
</body>

1

只是爲了提高Duopixel答案,運行過程中出現無限animitation時,我必須做的:

$(".box").css("animation-iteration-count", "1"); 
$(".box").bind("webkitAnimationEnd mozAnimationEnd animationEnd", function(){ 
    $(this).removeClass("animated") 
}) 
$(".box").hover(function(){ 
    $(".box").css("animation-iteration-count", "infinite"); 
    $(this).addClass("animated");   
}) 

這只是不會突然結束動畫。

+0

如果我想在我移除懸停時優雅地停止動畫,該怎麼辦?然後當我再次懸停時再次啓動無限動畫? – Vinay

+0

您可以實現該框的mouseleave事件,您可以添加此代碼。 –

+0

開發了一個解決方案:D 這裏的小提琴,如果它可以幫助任何人! http://jsfiddle.net/sSYYE/33/ – Vinay