悬停时循环旋转

时间:2014-08-24 04:03:26

标签: javascript jquery rotation

我试图让我的网站上的一些元素在悬停时循环旋转。我已经用css关键帧动画完成了它,但是当我鼠标移开或移出时,元素就会疯狂地跳跃。

所以我尝试使用一些花哨的jQuery(因为我已经将它加载到我的页面上)并且遇到了this very helpful stack,答案解释了如何使用悬停循环。但解释是为了运动。我设法用悬停移动它,但旋转很酷(如果可以处理的话,甚至两者都可以。)

循环代码:

$.fn.loopingAnimation = function(props, dur, eas) {

  if (this.data('loop') === true)
    {
       this.animate( props, dur, eas, function() {
           if( $(this).data('loop') === true ) $(this).loopingAnimation(props, dur, eas);
       });
    }

    return this; // Don't break the chain
};

$("#animate").hover(function(){
     $(this).data('loop', true).stop().loopingAnimation({ 'margin-top': '50px'}, 500).loopingAnimation({'margin-top':'10px'},500);
}, function(){
     $(this).data('loop', false).stop();
     // Now our animation will stop after fully completing its last cycle
});

然后我遇到了another stack,它解释了如何使用jQuery动画旋转,但现在我似乎无法将两个代码融合在一起......

旋转代码:

$(document).ready(function (){

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

我让a pen with both codes让事情变得更轻松。谁知道怎么做?

1 个答案:

答案 0 :(得分:1)

以下情况如何?

function AnimateRotate(elt, d, duration, ondone){
    $({deg: 0}).animate({deg: d}, {
        easing: 'linear',
        duration: duration,
        step: function(now, fx){
            $(elt).css({
                 transform: "rotate(" + now + "deg)"
            });
        },
        complete: ondone.bind(elt)
    });
}

$.fn.loopingRotation = function(msPerRotation) {
    if (this.data('rotating') === true) // already rotating
        return;
    this.data('rotating', true);
    AnimateRotate(this, 360, msPerRotation, function() {
        if (this.data('rotating') !== true)
            return;
        this.data('rotating', false);
        $(this).loopingRotation(msPerRotation);
    });
}
$.fn.stopRotation = function() {
    this.data('rotating', false);
}

$("#rotate").hover(function(){
     $(this).loopingRotation(1000);
}, function(){
     $(this).stopRotation();
});
相关问题