javascript - anchor 链接偏移仅在第一次单击时不起作用

标签 javascript

下面是我的JS代码。我有一个带有滚动 anchor 链接的页面。我需要用户在单击链接时转到页面上的特定部分,而不覆盖该部分的基本标题。

这就是我已经能够完成的事情(当然,在 Stackoverlfow 调查的帮助下)。

// 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).

上面的代码似乎有效,但问题是它仅在我第二次单击任何 anchor 时才有效。为什么它不会在第一条领带上触发?我知道它与 hashchange 有关,因此 javascript 从第二个链接开始只是因为存在 hashchange。你能给我一个解决方案吗?

最佳答案

window.onload = function () {
  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 m
};
<a href="#hello">Hello</a>
<div style="height: 300px;background:#ccc">spacer</div>
<div id="hello">Hello there!</div>
<div style="height: 300px;background:#ccc">spacer</div>

希望这有帮助

关于javascript - anchor 链接偏移仅在第一次单击时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40179520/

相关文章:

javascript - 使用 Phonegap 捆绑 Assets

Javascript 监听图像加载调用并在图像加载之前更改 src

javascript - 将变量设置为等于函数的返回值

javascript - 使用来自不同 HTML 属性的项目填充数组

javascript - Highcharts:向图表添加线条会从 X 轴删除标签

Javascript 更改按钮文本

javascript - jQuery 效果表达式引擎

javascript - 如何使用 ajax 发布 json 对象?

javascript - 我应该为选项卡组件使用 react-router 吗?

javascript - javascript 中重复使用 ID