3

我使用 JQuery 进行了一个小型动画工作:一张#photos包含 9 张照片的表格,我想使用animate鼠标悬停时的功能来增加宽度和高度。但是,如果用户将鼠标移到另一张照片上,则动画正在运行时,它会自动触发下一个动画,因此完全混乱。我应该怎么办?我的代码是:

$(function(){
  $("#photos tr td img").mouseover(function(){
    $(this).animate({"width":"1000px","height":"512px"},2000)
  });
  $("#photos tr td img").mouseout(function(){
    $(this).animate({"width":"100px","height":"50px"},2000)
  });       
});
4

5 回答 5

6

JQuery 在动画完成时提供回调。然后它可能看起来像这样:

var animating = false;
$(function(){ $("#photos tr td img").mouseover(
    function()
    {
        if(!animating)
            $(this).animate({"width":"1000px","height":"512px"},2000, easing, function() { animating = true; });
    }); 

    $("#photos tr td img").mouseout(
        function()
        {
            $(this).animate({"width":"100px","height":"50px"},2000, easing, function() { animating = false; }) 
        });
});
于 2009-07-03T11:41:15.510 回答
4

您应该在开始新的动画之前停止任何正在运行的动画以避免混乱。对于这个特定问题,这可能是最好和最直接的解决方案。

$(function(){
  $("#photos tr td img").mouseover(function(){
    $(this).stop();
    $(this).animate({"width":"1000px","height":"512px"},2000)
  });
  $("#photos tr td img").mouseout(function(){
    $(this).animate({"width":"100px","height":"50px"},2000)
  });       
});
于 2009-07-03T11:52:28.197 回答
1

我想答案取决于你想在第二个鼠标悬停上发生什么(而第一个鼠标悬停仍在动画中)。

1)如果你不想发生任何事情,你可以让你的第一个悬停在整个 TR 上设置一个“动画”状态,可能是这样的:

  $tr = $(this).closest("tr");
  if ($tr.data("animating") != true) {
      $tr.data("animating",true);
      $(this)
        .stop(true,false)
        .animate({"width":"1000px","height":"512px"},2000, function(){
          $tr.data("animating",false);
      });
  }

2) 如果您希望原始动画结束以便您的新图像可以动画,您需要 .stop() 将 clearQueue 和 goToEnd 参数设置为 true 的旧动画。这将确保额外的排队事件(来自一大堆悬停)不会仅仅持续几分钟,它会使动画立即跳到其最终状态:

  $(this).closest("tr").find("img:animated").stop(true,true);
  $(this).animate({"width":"1000px","height":"512px"},2000});
于 2009-07-03T20:08:56.860 回答
1

除了其他答案之外,我还会考虑使用hoverIntent插件。这只是避免了当用户将鼠标扫过所有照片时引发大量动画队列。只有当用户实际悬停时,您才真正想要动画。

于 2009-07-03T12:02:30.700 回答
0

始终检查元素的队列动画,从现在开始永远不会发生冲突:

$(function(){
  $("#photos tr td img").mouseover(function(){
    if($(this).queue("fx").length == 0)
       $(this).animate({"width":"1000px","height":"512px"},2000)
  });
  $("#photos tr td img").mouseout(function(){
       $(this).animate({"width":"100px","height":"50px"},2000)
  });       
});
于 2012-06-20T09:27:21.073 回答