LoginSignup
0
0

More than 3 years have passed since last update.

【JavaScript】別ページからアンカーリンク移動時の、固定ヘッダー分ずれ解消

Last updated at Posted at 2020-05-30

移動先ページのURLにハッシュが含まれていれば、ヘッダー分移動してあげるというシンプルな作りです。

ミソはsetTimeOutで、これがないとうまくいきません。
headerHeightの値を取得する前にwindow.scrollByが終わってしまうということでしょうか。

document.addEventListener("DOMContentLoaded", () => {
  if (location.hash) {
    const headerHeight = document.getElementById("js-header").clientHeight;
    setTimeout(() => {
      window.scrollBy(0, - headerHeight);
    },100)
  }
})
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0