【问题标题】:How to calculate the lower limit of a div and scroll to the next div?如何计算一个div的下限并滚动到下一个div?
【发布时间】:2015-04-23 06:29:04
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery html scroll mousewheel


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-04
      • 2012-12-03
      • 2013-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多