2012-02-10 53 views
1

我試圖淡入div,當它滾動到視圖從0.4到1,但工作正常,但我得到它退色到0.4時,用戶有滾動過去。我怎樣才能做到這一點?我怎樣才能讓我的div退色與jquery

tiles = $("#project_images img").fadeTo(0, 0.4); // set the default image opacity to semi transparent 

    $(window).scroll(function(d,h) { 
     tiles.each(function(i) { 
      a = $(this).offset().top + $(this).height(); 
      b = $(window).scrollTop() + $(window).height(); 
      if (a < b) $(this).fadeTo(1040,1); // when scrolling down over the image fade it IN. 
      if (a > b) $(this).fadeTo(1040, 0.4); // when scrolling down over the image fade it OUT. 
     }); 
    }); 

回答

1

這裏實現你的需求的一種方式。我沒有適應你的邏輯,而是從頭開始考慮它。它歸結爲:

/** 
* on scroll, for each image do the following 
*/ 

var visible = /** is the image at all visible in the viewport? */ ; 
var allVisible = /** is the image totally within the viewport? */ ; 

if (visible) { 
    if (allVisible) { 
     $(this).stop().fadeTo(1040, 1); 
    } else { 
     $(this).stop().fadeTo(1040, 0.4); 
    } 
} 

jQuery的stop()用於防止在圖像上排隊fadeTo動畫的積累。我在演示中的代碼爲了可讀性犧牲了計算的次數,但隨時輕鬆刷新並按您的喜好進行優化。

+0

真棒隊友,感謝您的幫助! :) – Farreal 2012-02-11 09:42:03

+0

當然可以。我可能會在不久的將來使用這個 – paislee 2012-02-11 15:59:17

+0

偉大的:)我現在在一個投資組合網站上使用它。它非常適合讓用戶專注於單個圖像,而不是一次查看所有圖像 – Farreal 2012-02-12 12:35:32