您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使锚链接在其链接位置上方一些像素

使锚链接在其链接位置上方一些像素

window.addEventListener(“hashchange”, function () { window.scrollTo(window.scrollX, window.scrollY - 100); });

这将允许浏览器为我们完成跳转到锚点的工作,然后我们将使用该位置进行偏移。

正如@erb指出的那样,仅当您在页面上更改哈希值时,此方法才有效。输入#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。

如少数人所指出的,如果您连续两次单击同一锚点链接,则以上操作将失败,因为没有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);
其他 2022/1/1 18:14:27 有508人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶