2012-02-10 68 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