CSS转换尚无法与jQuery动画化。您可以执行以下操作:
function AnimateRotate(angle) { // caching the object for performance reasons var $elem = $('#MyDiv2'); // we use a pseudo object for the animation // (starts from `0` to `angle`), you can name it as you want $({deg: 0}).animate({deg: angle}, { duration: 2000, step: function(now) { // in the step-callback (that is fired each step of the animation), // you can use the `now` paramter which contains the current // animation-position (`0` up to `angle`) $elem.css({ transform: 'rotate(' + now + 'deg)' }); } });}而且,顺便说一句:您不需要在jQuery 1.7+之前为CSS3转换添加前缀
更新资料
您可以将其包装在jQuery插件中,以使您的生活更轻松:
$.fn.animateRotate = function(angle, duration, easing, complete) { return this.each(function() { var $elem = $(this); $({deg: 0}).animate({deg: angle}, { duration: duration, easing: easing, step: function(now) { $elem.css({transform: 'rotate(' + now + 'deg)' }); }, complete: complete || $.noop }); });};$('#MyDiv2').animateRotate(90);更新2
我优化了一点,使的顺序
easing,
duration和
complete微不足道。
$.fn.animateRotate = function(angle, duration, easing, complete) { var args = $.speed(duration, easing, complete); var step = args.step; return this.each(function(i, e) { args.complete = $.proxy(args.complete, e); args.step = function(now) { $.style(e, 'transform', 'rotate(' + now + 'deg)'); if (step) return step.apply(e, arguments); }; $({deg: 0}).animate({deg: angle}, args); });};更新2.1
感谢matteo,他指出了
thiscomplete-中的-context 问题
callback。如果已修复,则通过在每个节点上将回调与 绑定 在一起
jQuery.proxy。
在 Update 2 之前,我已经将该版本添加到了代码中。
更新2.2
如果您想做类似来回切换旋转的操作,这是一个可能的修改。我只是向该函数添加了一个开始参数,并替换了这一行:
$({deg: start}).animate({deg: angle}, args);如果任何人都知道如何针对所有用例进行通用设置,无论他们是否要设置开始程度,请进行适当的编辑。
用法…非常简单!
主要有两种方法可以达到预期的效果。但是首先,让我们看一下参数:
jQuery.fn.animateRotate(angle, duration, easing, complete)
除“ angle”外,其他所有参数都是可选的,并回
jQuery.fn.animate退到默认的-properties:
duration: 400easing: "swing"complete: function () {}第一
这种方法虽然很短,但是我们传入的参数越多,看起来就越不清楚。
$(node).animateRotate(90);$(node).animateRotate(90, function () {});$(node).animateRotate(90, 1337, 'linear', function () {});第二名
如果有三个以上的参数,我更喜欢使用对象,因此此语法是我的最爱:
$(node).animateRotate(90, { duration: 1337, easing: 'linear', complete: function () {}, step: function () {}});


