2010-11-12 276 views
6

我試圖用jQuery實現this effectjQuery圖像懸停效果

我寫了一些代碼,但它是越野車(移到右下角,你會看到)。
check it out

基本上,如果有,你知道的,它這個,我會使用它,如果不是很高興已經建成的jQuery插件,用我的公式任何幫助,將不勝感激。這是我在數學課上不注意的地方:)

在此先感謝。

Maikel

回答

7

總的來說,我認爲這是你在找什麼:

$.fn.sexyImageHover = function() { 
    var p = this, // parent 
     i = this.children('img'); // image 

    i.load(function(){ 
     // get image and parent width/height info 
     var pw = p.width(), 
      ph = p.height(), 
      w = i.width(), 
      h = i.height(); 

     // check if the image is actually larger than the parent 
     if (w > pw || h > ph) { 
      var w_offset = w - pw, 
       h_offset = h - ph; 

      // center the image in the view by default 
      i.css({ 'margin-top':(h_offset/2) * -1, 'margin-left':(w_offset/2) * -1 }); 

      p.mousemove(function(e){ 
       var new_x = 0 - w_offset * e.offsetX/w, 
        new_y = 0 - h_offset * e.offsetY/h; 

       i.css({ 'margin-top':new_y, 'margin-left':new_x }); 
      }); 
     } 
    }); 
} 

You can test it here

值得注意的變化:

  • new_xnew_y應由圖像被劃分高度/寬度,而不是在容器的高度/寬度,這是更寬。
  • this已經是一個$.fn.plugin函數中的jQuery對象,不需要包裝它。
    • ip也jQuery的對象,沒有必要繼續它們包裹
  • 沒有必要對mouseenter結合mousemove(這將重新綁定)時,你在裏面反正mousemove纔會發生。
+0

除此之外,它是不完全一樣的例子。我不能放棄描述它,但有些事情是關閉的。 – 2010-11-12 02:54:31

+0

感謝尼克,修正了它:) – Maikel 2010-11-12 02:56:52

+1

@Glenn - 它沒有緩動,它絕對是一個更簡化的版本,我只是顯示如何修復當前的代碼:) – 2010-11-12 02:58:17

3

Nick Craver打了我約10分鐘的答案,但這是我的代碼,使用background-image來定位圖像,而不是實際的圖像。

var img = $('#outer'), 
    imgWidth = 1600, 
    imgHeight = 1200, 
    eleWidth = img.width(), 
    eleHeight = img.height(), 
    offsetX = img.offset().left, 
    offsetY = img.offset().top, 
    moveRatioX = imgWidth/eleWidth - 1, 
    moveRatioY = imgHeight/eleHeight - 1; 


img.mousemove(function(e){ 
    var x = imgWidth - ((e.pageX - offsetX) * moveRatioX), 
     y = imgHeight - ((e.pageY - offsetY) * moveRatioY); 
    this.style.backgroundPosition = x + 'px ' + y + 'px'; 
}); 

的變量巨大量是有,因爲mousemove事件處理程序必須儘可能高效。它稍微有些限制,因爲你需要知道尺寸,但我認爲代碼可以很容易地改變,以便與img s一起工作,因爲它的尺寸可以很容易地計算出來。

A的這個簡單的演示:http://www.jsfiddle.net/yijiang/fq2te/1/

從慢慢來停止
+0

應該注意的是,這對原始文件有一些限制,例如你需要知道尺寸。這就是說,這是很多情況下的好選擇,+1。 – 2010-11-12 03:17:53