我正在创建一个跨浏览器兼容的旋转(ie9),我有一个
jsfiddle以下代码
- $(document).ready(function () {
- DoRotate(30);
- AnimateRotate(30);
- });
- function DoRotate(d) {
- $("#MyDiv1").css({
- '-moz-transform':'rotate('+d+'deg)','-webkit-transform':'rotate('+d+'deg)','-o-transform':'rotate('+d+'deg)','-ms-transform':'rotate('+d+'deg)','transform': 'rotate('+d+'deg)'
- });
- }
- function AnimateRotate(d) {
- $("#MyDiv2").animate({
- '-moz-transform':'rotate('+d+'deg)','transform':'rotate('+d+'deg)'
- },1000);
- }
CSS和HTML真的很简单,只是为了演示:
- .SomeDiv{
- width:50px;
- height:50px;
- margin:50px 50px;
- background-color: red;}
- <div id="MyDiv1" class="SomeDiv">test</div>
- <div id="MyDiv2" class="SomeDiv">test</div>
使用.css()时旋转工作,但使用.animate()时不工作。为什么是这样,有办法解决它吗?
谢谢。
解决方法
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)'
- });
- }
- });
- }
您可以在这里阅读更多关于步骤回调的信息:http://api.jquery.com/animate/#step
和,btw:你不需要使用jQuery 1.7前缀css3 transforms
更新
你可以在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);
http://jsbin.com/ofagog/2/edit
Update2
我优化了一点,使顺序的顺序,持续时间和完全不重要。
- $.fn.animateRotate = function(angle,complete) {
- var args = $.speed(duration,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谁注意到这个上下文在完整的回调中的问题。如果固定它通过绑定回调与jQuery.proxy在每个节点上。
用法…很简单!
主要有两种方法来达到所需的结果。但首先,让我们来看看参数:
jQuery.fn.animateRotate(angle,duration,easing,complete)
除了“角度”都是可选的,并回退到默认的jQuery.fn.animate-properties:
- duration: 400
- easing: "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 () {}
- });