JS平滑滚动,滚动到最终/底部div的底部而不是顶部

3
我有一个链接可以滚动到同一页的不同区域。因此,为了避免页面跳跃,我添加了一些JavaScript平滑滚动(见下文)。
问题是,该脚本将页面滚动到目标div的顶部。它使用一些缓动来做到这一点,因此随着它到达最终div,它会减速。这很好,但如果最后一个div小于浏览器窗口的高度,则永远无法滚动到div的顶部。它只会撞到页面底部,看起来很糟糕,因为没有缓动。
我已经尝试了几种方法来使最后一个div滚动到div的底部,但都无济于事。有什么办法吗?
我在这里制作了一个jsfiddle展示了这个问题:https://jsfiddle.net/gky7y6gu/2/
$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});
1个回答

2
我添加了一些逻辑,以确保scrollTop永远不超过body的高度减去窗口的高度。这样,easeOut总是可见的。 https://jsfiddle.net/gky7y6gu/3/
$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      if (target.length) {
        var scrollTo = target.offset().top;
        var bodyHeight = $('body').height();
        var windowHeight = $(window).height();
        if (bodyHeight - windowHeight < scrollTo) {
          scrollTo = bodyHeight - windowHeight;
        }
        $('html,body').animate({
          scrollTop: scrollTo
        }, 1000);
        return false;
      }
    }
  });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接