jquery为旋转div设置动画

use*_*035 5 css jquery rotation jquery-animate

我想在动画函数中旋转div,例如

 $('div').animate({rotate: '30deg'},1000);
Run Code Online (Sandbox Code Playgroud)

我发现了这个:

http://www.zachstronaut.com/posts/2009/08/07/jquery-animate-css-rotate-scale.html

但我想知道是否有更正式的方式来做或至少以不同的方式.

谢谢

vyn*_*ynx 9

如果您愿意将CSS3与jQuery结合使用,那么这个方法可能会对您有所帮助:

HTML

<div id="click-me">Rotate</div>

<div id="rotate-box"></div>
Run Code Online (Sandbox Code Playgroud)

CSS

#rotate-box{

   width:50px;
   height:50px;
   background:#222222;

}

@-moz-keyframes rotatebox /*--for firefox--*/{

    from{
        -moz-transform:rotate(0deg);
    }       
    to{
        -moz-transform:rotate(360deg);
    }                       

}

@-webkit-keyframes rotatebox /*--for webkit--*/{

    from{
        -webkit-transform:rotate(0deg);
    }       
    to{
        -webkit-transform:rotate(360deg);
    }                       

}

#click-me{
   font-size:12px;
   cursor:pointer;
   padding:5px;
   background:#888888;
}
Run Code Online (Sandbox Code Playgroud)

假设有问题的元素应该在点击链接/ div /按钮时旋转,你的jQuery将如下所示:

jQuery的

$(document).ready(function(){
    $('#click-me').click(function(){
        $('#rotate-box').css({

        //for firefox
        "-moz-animation-name":"rotatebox",
        "-moz-animation-duration":"0.8s",
        "-moz-animation-iteration-count":"1",
            "-moz-animation-fill-mode":"forwards",

        //for safari & chrome
        "-webkit-animation-name":"rotatebox",
        "-webkit-animation-duration":"0.8s",
        "-webkit-animation-iteration-count":"1",
        "-webkit-animation-fill-mode" : "forwards",

        });
    });
});
Run Code Online (Sandbox Code Playgroud)

因此,由于jQuery还不能支持.animate()中的rotate(deg),我有点想通过在CSS3中预定义动画关键帧并为该特定动画分配标签或标识符来欺骗.在此示例中,该标签/标识符定义为rotatebox.

从这里开始的是,点击可点击div的那一刻,jQuery片段将使用.css()并将必要的属性分配给可旋转元素.分配这些属性的那一刻起,将存在从元素到CSS3动画关键帧的桥梁,从而允许动画执行.您还可以通过更改animation-duration属性来控制动画的速度.

我个人认为只有在需要单击或鼠标滚动事件来激活旋转时才需要此方法.如果在文档加载时应该立即运行rotate,那么单独使用CSS3就足够了.这同样适用于如果悬停事件应该激活旋转 - 您只需定义将元素链接到元素的伪类中的旋转动画的CSS3动画属性.

我的方法只是基于这样的假设,即需要一个click事件来激活旋转,或者jQuery在某种程度上需要在其中扮演一个角色.我知道这种方法非常繁琐,所以如果有人有输入,请随时提出建议.请注意,由于此方法涉及CSS3,因此在IE8及以下版本中无法正常工作.


raj*_*_kw 5

我觉得最简单的是jsfiddle上的这个示例

$(function() {
    var $elie = $("img"), degree = 0, timer;
    rotate();
    function rotate() {

        $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});  
        $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
        $elie.css('transform','rotate('+degree+'deg)');                      
        timer = setTimeout(function() {
            ++degree; rotate();
        },5);
    }

    $("input").toggle(function() {
        clearTimeout(timer);
    }, function() {
        rotate();
    });
}); 
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/eaQRx/