0

首次加载我的网页时,我的起始 div 使用以下 CSS 代码旋转:

    @keyframes rotate
    {
    from {    transform:rotate(0deg);
    -ms-transform:rotate(0deg); 
    -webkit-transform:rotate(0deg); }

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

    @-webkit-keyframes rotate 
    {
    from {    transform:rotate(0deg);
    -ms-transform:rotate(0deg); 
    -webkit-transform:rotate(0deg); }

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

旋转之后,这段代码就没用了。我想要它,所以当单击按钮时,它会再次进行此旋转。为此,我需要能够将此 css 代码放入一个javascript/jQuery函数中,以便我可以随时调用它。这可能吗?

4

3 回答 3

2

试试这个

   $({deg: 0}).animate({deg: d}, {
            duration: 2000,
            step: function(now){
                elem.css({
                     transform: "rotate(" + now + "deg)"
                });
            }
        });

JSFIDDLE DEMO

于 2013-08-17T11:23:36.420 回答
2

只需将 CSS 属性和所需的值应用于 jQuery

演示

$(' #box ').css({
    transition: '2s linear',
    transform: 'rotate(360deg)'
});

PS:jQuery 将为您处理所有那些 -browser-specific 前缀。

于 2013-08-17T11:29:47.117 回答
2

您可以将动画行为包装到一个类中,例如:

.rotate{
  -webkit-animation: rotate 4s;
  /* more prefixes if you want to */
  animation: rotate 4s;
}

然后,您可以在单击按钮时应用该类,例如:

$('#myButton').click(function(){
  $('#myElementToAnimate').addClass('rotate');
});

要在动画完成后删除该类,您必须侦听以下animationend事件:

$('#myButton').click(function(){
  // all the different event names are due to the fact that this isn't fully standardized yet
  $('#myElementToAnimate').addClass('rotate').on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function(){
    $(this).removeClass('rotate');
  });
});

这应该比使用基于 JavaScript 的动画为您提供更流畅的结果。看到这个演示小提琴

于 2013-08-17T11:30:50.037 回答