2016-05-16 72 views
1

我目前使用以下方式为我的网站上的某些容器的滚动淡入淡出,但是,由于我的一些容器有很大的高度,是否有方法可以更改它当窗口的底部位于容器的中心而不是容器的底部时,它会渐渐消失?另外,有没有一种方法来指定像素?淡入滚动 - 容器中心

$(window).scroll(function() { 

    /* Check the location of each desired element */ 
    $('.container').each(function (i) { 

     var bottom_of_object = $(this).offset().top + $(this).outerHeight(); 
     var bottom_of_window = $(window).scrollTop() + $(window).height(); 

     /* If the object is completely visible in the window, fade it it */ 
     if (bottom_of_window > bottom_of_object) { 

      $(this).animate({ 
       'opacity': '1' 
      }, 500); 

     } 
    }); 
}); 

回答

1

这样的事情?

$(window).scroll(function() { 

    /* Check the location of each desired element */ 
    $('.container').each(function (i) { 

     var top_of_object = $(this).offset().top; 
     var middel_of_window = $(window).scrollTop() + ($(window).height()/2); 

     /* If the object is completely visible in the window, fade it in */ 
     if (middel_of_window > (top_of_object + 300)) { 

      $(this).animate({ 
       'opacity': '1' 
      }, 500); 

     } 
    }); 
}); 

希望它可以帮助你。

+0

它确实谢谢你,但它仍然不是很适合我的几个容器。 有没有一种方法来指定像素?例如当窗口的底部是300像素的容器然后淡入? –

+0

@MikeRainsbury [文档说返回值是以像素为单位的](http://www.w3schools.com/jquery/css_offset.asp),因此在动画之前添加300将中间的300px放入obj中。 –