平滑页面滚动偏移取决于元素高度

时间:2014-08-06 22:54:36

标签: jquery scroll offset smooth

使用平滑的页面滚动在单页网站的各个部分之间导航。需要帮助找到一种方法,使元素不滚动到最顶部,而是转移到某个页面元素的高度(在本例中为“nav”)定义的偏移距离。我找到了一个使用静态数字的解决方案,但这不会削减它,因为固定导航栏的高度会在各个断点处发生变化。因此,在下面的小提琴示例中,如果屏幕宽度<400px,则偏移将获得导航器50px的高度并使用该...并且如果屏幕是400px +,则将使用100px。这可能吗?

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

小提琴:http://jsfiddle.net/pixeloco/b3Lrdmam/

1 个答案:

答案 0 :(得分:0)

这样做:

scrollTop: target.offset().top - $('nav').height()

Demo

相关问题