使用jQuery动画化CSS变换

我正在尝试为div设置动画,让它围绕y轴旋转180度。 当我调用以下代码时,我得到一个jQuery错误:

$("#my_div").animate({ "transform": "rotateY(180deg)", "-webkit-transform": "rotateY(180deg)", "-moz-transform": "rotateY(180deg)" }, 500, function() { // Callback stuff here }); }); 

它说“Uncaught TypeError:无法读取未定义的属性’defaultView’并且说它在jQuery文件本身中……我做错了什么?

您还可以在CSS类中预定义旋转并使用jQuery添加/删除该类:

CSS:

 #my_div { -moz-transition: all 500ms ease; -o-transition: all 500ms ease; -webkit-transition: all 500ms ease; transition: all 500ms ease; } .rotate { -moz-transform: rotate(180deg); -o-transform: rotate(180deg); -webkit-transform: rotate(180deg); transform: rotate(180deg); } 

jQuery的:

 $("#my_div").addClass('rotate'); 

试试这个:

 $('#myDiv').animate({ textIndent: 0 }, { step: function(go) { $(this).css('-moz-transform','rotate('+go+'deg)'); $(this).css('-webkit-transform','rotate('+go+'deg)'); $(this).css('-o-transform','rotate('+go+'deg)'); $(this).css('transform','rotate('+go+'deg)'); }, duration: 500, complete: function(){ alert('done') } }); 

http://jsfiddle.net/RPSzb/2/

jQuery无法为转换属性提供开箱即用的动画。 但您可以使用.animate()自定义属性设置动画,并使用step函数 “手动”进行转换:

 var $myDiv = $("#my_div"), ccCustomPropName = $.camelCase('custom-animation-degree'); $myDiv[0][ccCustomPropName ] = 0; // Set starting value $myDiv.animate({ccCustomPropName : 180}, { duration: 500, step: function(value, fx) { if (fx.prop === ccCustomPropName ) { $myDiv.css('transform', 'rotateY('+value+'deg)'); // jQuery will add vendor prefixes for us } }, complete: function() { // Callback stuff here } }); 

请参阅此小提琴以获取工作示例(单击蓝色框)。

这类似于undefined的答案,但它没有滥用真正的CSS属性。

注意:自定义属性的名称应该是jQuery.camelCase()名称,因为.animate()在内部使用camelCased名称,因此,将使用camelCased名称存储属性的当前值, fx.prop也将是以camel为基础的名字。

忘记jQuery的$.animate() ,而不是使用$.velocity() 。 Velocity.js是jQuery的动画扩展。 它使用与jQuery相同的语法,并允许您为CSS3制作动画,例如3D变换,平移,旋转,褪色,过渡,倾斜……任何你想要的东西。 而且因为它很聪明,在可能的情况下使用CSS3而不是JS,它的动画效果也会更好。 我不明白为什么jQuery还没有这样做!

http://julian.com/research/velocity/