window.addEventListener("hashchange", function () {
window.scrollTo(window.scrollX, window.scrollY - 100);
});
这将允许浏览器为我们完成跳转到锚点的工作,然后我们将使用该位置进行偏移。
编辑1:
正如@erb 所指出的,这仅适用于您在页面上同时更改哈希值的情况。输入#something
URL 中已有的页面不适用于上述代码。这是处理该问题的另一个版本:
// The function actually applying the offset
function offsetAnchor() {
if(location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 100);
}
}
// This will capture hash changes while on the page
window.addEventListener("hashchange", offsetAnchor);
// This is here so that when you enter the page with a hash,
// it can provide the offset in that case too. Having a timeout
// seems necessary to allow the browser to jump to the anchor first.
window.setTimeout(offsetAnchor, 1); // The delay of 1 is arbitrary and may not always work right (although it did in my testing).
注意:要使用 jQuery,您可以在示例中window.addEventListener
替换为。$(window).on
谢谢@霓虹灯。
编辑2:
正如一些人所指出的,如果您连续两次或多次单击同一锚链接,上述操作将失败,因为没有hashchange
事件强制偏移。
此解决方案是@Mave 建议的略微修改版本,并使用 jQuery 选择器为简单起见
// The function actually applying the offset
function offsetAnchor() {
if (location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 100);
}
}
// Captures click events of all <a> elements with href starting with #
$(document).on('click', 'a[href^="#"]', function(event) {
// Click events are captured before hashchanges. Timeout
// causes offsetAnchor to be called after the page jump.
window.setTimeout(function() {
offsetAnchor();
}, 0);
});
// Set the offset when entering page with hash present in the url
window.setTimeout(offsetAnchor, 0);
这个例子的 JSFiddle 在这里