window.addEventListener("hashchange", function () {
window.scrollTo(window.scrollX, window.scrollY - 100);
});
这将允许浏览器为我们完成跳转到锚点的工作,然后我们将使用该位置进行偏移。
编辑1:
正如@erb所指出的那样,这只有在更改哈希时在页面上时才有效。输入URL中已有的页面不适用于上述代码。这是另一个版本来处理这个问题:#something
// 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
。谢谢@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 在这里