Cross-Browser CSS Rotation with jQuery.animate()
Problem:
Performing CSS rotation animations using jQuery.animate() fails to work cross-browser. The rotation works when using .css(), but not when using .animate().
Cause:
CSS-Transforms cannot be directly animated with jQuery.
Solution:
To perform CSS-Transform animations using jQuery, you can use the following alternative method:
function AnimateRotate(angle) { var $elem = $('#MyDiv2'); $({deg: 0}).animate({deg: angle}, { duration: 2000, step: function(now) { $elem.css({ transform: 'rotate(' + now + 'deg)' }); } }); }
Explanation:
This method uses a custom "step" callback function to update the "transform" property of the selected element at each step of the animation. The "step" function receives the current animation position (now) as a parameter, which you can use to calculate the desired rotation angle.
Plugin:
You can wrap this method into a jQuery plugin for easier use:
$.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 }); }); };
Usage:
To use the plugin, you can simply call:
$('#MyDiv2').animateRotate(90);
Updates:
The provided solution has been updated several times to improve efficiency and provide more flexibility.
Additional Usage Details:
The above is the detailed content of How Can I Achieve Cross-Browser CSS Rotation Animations with jQuery?. For more information, please follow other related articles on the PHP Chinese website!