2010-12-10 138 views
1

我有一個圖標的選擇,當我把鼠標懸停在它們上面時,會觸發一個動畫,這個動畫包括動畫不同圖像的左邊和上邊位置。然後,當我將鼠標移出圖標時,圖像會返回到原始狀態。麻煩的是,如果我真的很快地將光標移動到所有圖標上,則動畫圖像的左側和頂部位置不會像預期的那樣返回到其初始狀態。jquery動畫產生奇怪的結果

這裏的代碼 - 任何想法如何我可以整理這件事,並防止這個和任何進一步的問題?

$("div").hover(function() { 

     $(this).find("span").slideDown(100); 
     $(this).css("background-color","#89A7BA"); 
     var currentlyHovered = $(this).find("img").attr("id").replace("-icon", ""); 
     $("img#" + currentlyHovered + "-spot").animate({ 
      width: "17px", 
      height: "17px", 
      left: parseInt($("img#" + currentlyHovered + "-spot").css("left")) - 5, 
      top: parseInt($("img#" + currentlyHovered + "-spot").css("top")) - 5 
     }, 100); 


    }, function() { 

     $(this).find("span").slideUp(100); 
     $(this).css("background-color","#000"); 
     $("img#" + currentlyHovered + "-spot").animate({ 
      width: "7px", 
      height: "7px", 
      left: parseInt($("img#" + currentlyHovered + "-spot").css("left")) + 5, 
      top: parseInt($("img#" + currentlyHovered + "-spot").css("top")) + 5 
     }, 100); 
     currentlyHovered = ""; 

    }); 

對於任何有興趣的人,這裏是完整的解決方案。

$.fn.hoverAnimation = function() { 
     return this.each(function() { 
      var currentlyHovered = $(this).find("img").attr("id").replace("-icon", ""); 
      var originalLeft = parseInt($("img#" + currentlyHovered + "-spot").css("left")); 
      var originalTop = parseInt($("img#" + currentlyHovered + "-spot").css("top")); 
      return $(this).hover(function() { 
       $(this).find("span").slideDown(100); 
       $(this).css("background-color","#89A7BA"); 
       $("img#" + currentlyHovered + "-spot").animate({ 
        width: "17px", 
        height: "17px", 
        left: originalLeft - 5, 
        top: originalTop - 5 
       }, 100); 
      },function() { 
       $(this).find("span").slideUp(100); 
       $(this).css("background-color","#000"); 
       $("img#" + currentlyHovered + "-spot").animate({ 
        width: "7px", 
        height: "7px", 
        left: originalLeft, 
        top: originalTop 
       }, 100); 
      }); 
     }); 
    } 

    $("div").hoverAnimation(); 
+0

我很高興我的解決方案爲你工作。我非常喜歡將簡單但可重複的任務構建爲專門的jQuery插件。 – 2010-12-15 10:17:07

回答

1

我認爲它不回到原來的位置的原因是原始位置被視爲中間動畫。我建議建立一個簡單的插件爲你做:

$.fn.hoverAnimation = function() { 
    return this.each(function() { 
    var originalLeft = parseInt($("img#" + $(this).find(img).attr(id) + "-spot").css("left")); 
    var originalTop = parseInt($("img#" + $(this).find(img).attr(id) + "-spot").css("top")); 
    return $(this).hover(function() { 
     ... 
    },function() { 
     ... 
    }); 
    } 
}; 

$('div').hoverAnimation();