2012-01-30 84 views
0

對於使用jQuery的網站,頁面上有一些圖形,點擊時會在網站的另一部分顯示信息。當被淹沒時,圖像從中心擴展一個百分比。問題在於,當您快速進出鼠標(動畫完成之前)時,圖像無法正確調整大小。 (他們變得更小)從中心放大圖像的百分比?

$(".locationimg").hover(
     function(){ 
      var height = $(this).height() 
      var width = $(this).width() 
      var top = $(this).position().top 
      var left = $(this).position().left 
      $(this).stop().animate({ 
       height: height*1.1 + 'px', 
       width: width*1.1 + 'px', 
       top: top - (((height*1.1)-height)/2) + 'px', 
       left: left - (((width*1.1)-width)/2) + 'px' 
      }); 
     }, 
     function(){ 
      var height = $(this).height() 
      var width = $(this).width() 
      var top = $(this).position().top 
      var left = $(this).position().left 
      var height1 = height/1.1 
      var width1 = width/1.1 
      $(this).stop().animate({ 
       height: height1 + 'px', 
       width: width1 + 'px', 
       top: top - (((height1)-height)/2) + 'px', 
       left: left - (((width1)-width)/2) + 'px' 
      }); 
     } 
    ); 

如果這些變量可以再進.hover(定義),這將是容易的,因爲調整圖像大小,簡直是「高度:高度」等等。這樣做的問題是有幾個圖像都需要這樣做,所以變量需要在.hover()中定義。

回答

0

嘗試使用stop(false, true)而不僅僅是stop()。這意味着動畫將在新動畫開始之前「完成」。

此外,您可以使用data()函數在元素上存儲高度和寬度。

0

之前懸停(),你可以存儲每個數據的原始和縮放尺寸和位置屬性的圖像本身:而不是試圖計算在

$(".locationimg").each(function() { 
    var $this  = $(this), 
     origWidth = $this.width(), 
     origHeight = $this.height(), 
     zoomWidth = origWidth * 1.1, 
     zoomHeight = origHeight * 1.1, 
     pos  = $this.position(), 
     origTop = pos.top, 
     origLeft = pos.left 
     // ... also find zoomed top, left... 
    ; 
    $this.data({ 
     "origwidth": origWidth, 
     "origHeight": origHeight, 
     "zoomWidth": zoomWidth, 
     "zoomHeight": zoomHeight 
     /* etc. */ 
     /* ... also store top and left... */ 
    }); 
}).hover(
    // your hover code here 
) 

然後懸停處理程序中,飛,您可以只讀取已存儲的尺寸/位置,並在鼠標懸停時轉換爲縮放的尺寸,或在鼠標懸停時轉換爲原始尺寸。這也會快很多。