2022.03.10

別ページのアンカーリンクから画面遷移したのちにスムーススクロールを適用させる方法

スポンサーリンク

ヘッダーのメニュー内容を変えずにページ跨ぎでスムーススクロールを適用させたい場合

スムーススクロールを考慮しない場合、単純にアンカーリンクのhref要素の内容を以下のように置き換えるだけです。

https://サイト名/#リンク先

ですがこれだとヘッダーの高さの差分の影響で位置がズレたり、スムーススクロールが適用されません。
ここら辺ができていないと不格好なサイトになるので、やり方を備忘録として残すことにします。

 

コードの解説

では実際に見ていきます。

JavaScript

const smoothScroll = () => {
  //URLのアンカー(#~~)を取得
  let urlHash = location.hash;
  //URLにアンカー(#~~)が存在する場合True
  if (urlHash) {
    $('body,html').stop().scrollTop(0);
      setTimeout(function () {
        const adjustSP = -50;
        const adjustPC = -80;
        const speed = 500;
        let target2 = $(urlHash);
    //別ページ用のスムーススクロールの関数
    if (window.matchMedia("(min-width: 767px)").matches) {
      const position = target2.offset().top + adjustPC;
      $('body,html').stop().animate({ scrollTop: position }, speed, 'swing');
    } else {
      const position = target2.offset().top + adjustSP;
      $('body,html').stop().animate({ scrollTop: position }, speed, 'swing');
    }
  });
}
//通常(TOPページ用)のスムーススクロール
$('.p-header__list a[href^=#]').click(function () {
  const adjustSP = -50;
  const adjustPC = -80;
  const speed = 500;
  const href= $(this).attr("href");
  const target = $(href == "#" || href == "" ? 'html' : href);
  if (window.matchMedia("(min-width: 767px)").matches) {
    const position = target.offset().top + adjustPC;
    $('body,html').animate({scrollTop:position}, speed, 'swing');
  } else {
    const position = target.offset().top + adjustSP;
    $('body,html').animate({scrollTop:position}, speed, 'swing');
  }
  return false;
});

HTML (WordPress)

//シングルページ
<?php if ( is_single() ) : ?>
<ul class="p-header__list">
  <li class="p-header__item">
    <a class="p-header__anker u-single__adjust" href="http://localhost/#profile">profile</a>
  </li>
  <li class="p-header__item">
    <a class="p-header__anker u-single__adjust" href="http://localhost/#works">works</a>
  </li>
  <li class="p-header__item">
    <a class="p-header__anker u-single__adjust" href="http://localhost/#contact">contact</a>
  </li>
</ul>
<?php else:?>
//Topページ
<nav>
  <ul class="p-header__list">
    <li class="p-header__item">
      <a class="p-header__anker" href="#profile">profile</a>
    </li>
    <li class="p-header__item">
      <a class="p-header__anker" href="#works">works</a>
    </li>
    <li class="p-header__item">
      <a class="p-header__anker" href="#contact">contact</a>
    </li>
  </ul>
</nav>
<?php endif;?>


通常のスムーススクロール関数の中にもう一個別ページ用のスムーススクロール関数を作成します。

異なる箇所としては、 if(urlHash){} の部分になります。

urlHashが存在するかif文で条件分岐をかけるといった内容になっています。

別ページにて、ヘッダーの項目がクリックされた際、 if(urlHash){}  の中身に入ります。

これにより画面遷移してからもスムーススクロールが適用されます。