减去文档片段滚动的垂直偏移量



我有一个固定标题的页面,我想要一个像http://example.com#foo这样的url滚动到具有id=foo的元素,并减去标题的高度,以便该元素可见。

我尝试过以下,但至少在Chrome中,此代码在默认文档片段滚动发生之前运行,因此滚动位置被覆盖:

$(function() {
  var offset;
  if (window.location.hash !== "") {
     offset = $(window.location.hash).offset().top;
     return $("body").scrollTop(offset - headerHeight);
  }
});

下面是问题的概要http://jsfiddle.net/rk8y7/1/

我能够通过将DOM元素的id更改为当前id + _section,然后侦听hashchange事件来设置页面的滚动位置来实现这一点。我还必须在页面加载时触发hashchange以使其在第一个页面加载时工作。

$(function() {
  $(window).on('hashchange', function() {
    var elemId, headerHeight, offset;
    elemId = window.location.hash + "_section";
    if (window.location.hash !== "" && $(elemId).length) {
      headerHeight = $('header').height();
      offset = $(elemId).offset().top;
      return $("html, body").scrollTop(offset - headerHeight);
    }
  });
  $(window).trigger('hashchange');
});

这是我的小提琴http://jsfiddle.net/sguha095/rk8y7/4/

最新更新