如何计算div的下限并滚动到下一个div?

时间:2015-04-23 06:29:04

标签: javascript jquery html scroll mousewheel

当目前的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();
});

1 个答案:

答案 0 :(得分:0)

将元素的高度添加到偏移量

 $('#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();
    });