6

我试图仅在鼠标悬停在对象上时才运行动画。我可以获得动画的一次迭代,然后在鼠标移出时让它恢复正常。但我希望动画在鼠标悬停时循环播放。我将如何使用 setInterval?我有点卡住了。

4

4 回答 4

9

可以这样做:

$.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
}

现在,您可以这样做:

$("div.animate").hover(function(){
     $(this).data('loop', true).stop().loopingAnimation({ left: "+10px"}, 300);
}, function(){
     $(this).data('loop', false);
     // Now our animation will stop after fully completing its last cycle
});

如果您希望动画立即停止,您可以将hoverOut行更改为:

$(this).data('loop', false).stop();
于 2010-01-11T03:37:14.610 回答
4

我需要它来处理页面上的多个对象,所以我修改了一点 Cletus 的代码:

var over = false;
$(function() {
  $("#hovered-item").hover(function() {
    $(this).css("position", "relative");
    over = true;
    swinger = this;
    grow_anim();
  }, function() {
    over = false;
  });
});

function grow_anim() {
  if (over) {
    $(swinger).animate({left: "5px"}, 200, 'linear', shrink_anim);
  }
}

function shrink_anim() {
  $(swinger).animate({left: "0"}, 200, 'linear', grow_anim);
}
于 2011-05-04T11:58:48.693 回答
4

setInterval返回一个 id,可以传递给它clearInterval以禁用计时器。

您可以编写以下内容:

var timerId;

$(something).hover(
    function() {
        timerId = setInterval(function() { ... }, 100);
    },
    function() { clearInterval(timerId); }
);
于 2010-01-11T03:37:47.640 回答
1

考虑:

<div id="anim">This is a test</div>

和:

#anim { padding: 15px; background: yellow; }

和:

var over = false;
$(function() {
  $("#anim").hover(function() {
    over = true;
    grow_anim();
  }, function() {
    over = false;
  });
});

function grow_anim() {
  if (over) {
    $("#anim").animate({paddingLeft: "100px"}, 1000, shrink_anim);
  }
}

function shrink_anim() {
  $("#anim").animate({paddingLeft: "15px"}, 1000, grow_anim);
}

您也可以使用计时器来实现这一点。

于 2010-01-11T03:42:46.843 回答