2016-12-30 37 views
1

是否可以通過mouseover和animate.css來動畫元素?通過mouseover和animate.css動畫元素

$(document).ready(function(){ 
    $("p").mouseover(function(){ 
     $("p").css("background-color", "red"); 
     $("#mystyle").animateCss('bounce'); 
    }); 
    $("p").mouseout(function(){ 
     $("p").css("background-color", "gray"); 
    }); 
}); 

我試過了,但有些事情是錯的。 https://jsfiddle.net/f79b7033/

+0

如果你想使用'animateCss'功能,你需要把它列入你的代碼。檢查我的答案:) – Dekel

回答

3

按照documentation in animation.css,則可以使用擴展了jQuery:

$.fn.extend({ 
    animateCss: function (animationName) { 
     var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend'; 
     this.addClass('animated ' + animationName).one(animationEnd, function() { 
      $(this).removeClass('animated ' + animationName); 
     }); 
    } 
}); 

而且你沒有在你的代碼添加。

這裏是一個工作示例(包括上面的代碼):
https://jsfiddle.net/dekelb/9jaq7fhr/

2

我不熟悉animate.css但打開控制檯,你得到的錯誤:

Uncaught TypeError: $(...).animateCss is not a function 
    at HTMLParagraphElement.<anonymous> ((index):53) 
    at HTMLParagraphElement.dispatch (jquery-3.1.1.js:5201) 
    at HTMLParagraphElement.elemData.handle (jquery-3.1.1.js:5009) 

所以我看着爲animate.css的文檔,發現這個:

$('#yourElement').addClass('animated bounceOutLeft');

補充說,相反,這裏是你的小提琴 - 看起來像它的工作:

https://jsfiddle.net/f79b7033/3/

編輯: 德克爾指出,上述錯誤是由不延長jQuery的(看他怎麼辦這個問題的答案)引起的。這是非jQuery版本。

+0

使用'addClass'是一個選項,但如果您想使用'animateCss'函數,則需要擴展jQuery。閱讀我的答案以獲得更多關於此的信息。 – Dekel

+0

@Dekel有道理。猜猜我沒有閱讀足夠多的文檔:) Upvoted你的答案,因爲它是更好的答案,我會做一個解釋我的編輯是非JQuery的方式做到這一點 – Chris

+0

得到了你的投票也:) – Dekel