window.addEventListener(“hashchange”, function () {
window.scrollTo(window.scrollX, window.scrollY - 100);
});
这将允许浏览器为我们完成跳转到锚点的工作,然后我们将使用该位置进行偏移。
编辑1:
正如@erb指出的那样,仅当您在页面上更改哈希值时,此方法才有效。输入
#something网址中已经存在的页面不适用于上述代码。这是处理该问题的另一个版本:
// The function actually applying the offsetfunction offsetAnchor() { if(location.hash.length !== 0) { window.scrollTo(window.scrollX, window.scrollY - 100); }}// This will capture hash changes while on the pagewindow.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 offsetfunction 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 urlwindow.setTimeout(offsetAnchor, 0);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)