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
with替换为$(window).on
。谢谢@Neon。
编辑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在这里