Anchor Link Offset仅在第一次单击时不起作用

时间:2016-10-21 14:41:07

标签: javascript

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

这是我能够完成的事情(当然,在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).

上面的代码似乎有效,但问题是它只能在我第二次单击任何锚点时起作用。为什么它不会在第一个领带上发射?我知道它与hashchange有关,所以javascript从第二个链接开始只是因为有一个hashchange。你能给我一个解决方案吗?

1 个答案:

答案 0 :(得分:1)

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="#">
  Helo
  </a>

希望这有帮助