2015-04-23 77 views
1

我想滚动到下一个div当当前div几乎达到其下限。如何计算div的下限并滚动到下一个div?

我正在使用jQuery插件MouseWheel。我有下面的代码,当我滚动时运行动画scrollTop。但是,当它达到某个预期的点时,并不是它的下限。因为,一些div包含大量带有图片的文字。

这是结构HTML

<html> 
[...] 
<body> 
    <div id="main"> 
    <div class="item"> 
     [Only a Image] 
     <!-- Only a Img? I'm 2px distance to the next div OK, ScrollTop When Scroll1 --> 
    </div> 
    <div class="item"> 
     [Some Text] 
     <!-- mmmm Some text. Ok, I let you read this.. Scroll 1.. Scroll 2.. Scroll 3.. 
     Wait! I'm 40px distance to the next div ... scrollTop --> 
    </div> 
    <div class="item"> 
     [Some text with Image] 
     <!-- mmmm Some text with Image. Ok, I let you read this.. Scroll 1.. Scroll 2.. Scroll 3.. Scroll 4... Scroll 5.. Scroll 6.. 
     Wait! I'm 40px distance to the next div ... scrollTop --> 
    </div> 
    <div class="item"> 
     [....] 
    </div> 
    </div> 
</body> 
</html> 

这是JS:

$('#main').on('mousewheel', '.item', function(e) { 
    if (e.deltaY < 0) { 
     $('html, body').animate({ 
      scrollTop: $(e.currentTarget).next().offset().top 
     }, 1000); 

    } else { 
     $('html, body').animate({ 
      scrollTop: $(e.currentTarget).prev().offset().top 
     }, 1000); 
    } 
    e.preventDefault(); 
}); 

回答

0

元素的HIGHT添加到偏移

$('#main').on('mousewheel', '.item', function(e) { 
      if ($(document).scrollTop() >= $(e.currentTarget).offset().top+$(e.currentTarget).height();) { 
      $('html, body').animate({ 
       scrollTop: $(e.currentTarget).next().offset().top; 
      }, 1000); 

      } 
     e.preventDefault(); 
    }); 
+0

我与一些更新我的结构HTML注释。 – Dvex