我有一个带有固定标题的页面,我想要一个像 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);
}
});
这是问题的 jsfiddle 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');
});
这是我的 fiddle http://jsfiddle.net/sguha095/rk8y7/4/
关于javascript - 减去文档片段滚动的垂直偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17076304/