当滚动条到达特定位置时动画 div

Animate div when the scrollbar reaches certain position

我的网站目前在单个滚动布局中包含三个部分。带有两个部分的标题:关于和联系(这些是 div 框),当您滚动到页面底部时,它们会显示动画。我想要实现的是让动画在用户向下滚动并点击每个(div 框)部分的底部而不是网站底部时发生。

我认为我需要实施 .offset() 函数但不确定这是否正确?

如有任何帮助,我们将不胜感激。

CSS

.header {
  display: none;
  position: relative;
  left: 0px;
  right: 0px;
  top: 500px;
  height: 80px;
  width: 100%;
  background:red;
  color: #fff;
  text-align: center;
}

JS

var header = $('.header'),
extra = 10; // In case you want to trigger it a bit sooner than exactly at the bottom.

header.css({ opacity: '0', display: 'block' });

$(window).scroll(function() {

var scrolledLength = ( $(window).height() +extra) + $(window).scrollTop(),
   documentHeight =  $(document).height();

console.log( 'Scroll length: ' + scrolledLength + ' Document height: ' + documentHeight )

if( scrolledLength >= documentHeight ) {

   header
      .addClass('top')
      .stop().animate({ top: '20', opacity: '1' }, 800);
}
else if ( scrolledLength <= documentHeight && header.hasClass('top') ) {           
    header
       .removeClass('top')
       .stop().animate({ top: '500', opacity: '0' }, 800);
  } 
});

Fiddle - http://jsfiddle.net/SFPpf/480/

在这种情况下,position() 看起来会更好。 position 方法是相对于文档的,而 offset 是相对于父元素的。它 return 是一个具有属性 "top" 和 "left" 的对象。它一次只能 return 一个元素的位置,因此对于第一个 div,您需要使用 first() 和 eq() 来获取特定的位置。

.fillWindow 的底部将是其垂直位置 + 高度。

var $fillWindow = $(".fillWindow").first(), // or eq() for others
    position = $fillWindow.position(),
    height = $fillWindow.height();
    //bottom = position.top + height;

scrollTop() 现在可用于检查用户何时滚动经过 .fillWindow。

if ( $(window).scrollTop() >= position.top ) {
    // do the animation here
} else {
    // do something else
}

编辑:我刚刚发现了我的错误。它应该是 $(window).scrollTop()。您还应该只测试 scrollTop 是否位于 .fillWindow 的顶部。