LoginSignup
6
3

More than 3 years have passed since last update.

jQueryでページ内の指定箇所にヌルッと移動

Posted at

htmlで

<a hreh=“#about”>ABOUT</a>

とすれば、id属性に「about」がついた箇所に移動できますが、一瞬で画面が変わってしまい味気なさがあります。

そこでjQueryを使ってヌルッと移動させる方法を紹介します。

htmlは以下です。

<a class=“goSection” href=“#first”>FIRST</a>
<a class=“goSection” href=“#second”>SECOND</a>

  <section id="first">
    FIRST
  </section>

  <section id="second">
    SECOND
  </section>

goSectionというクラスがついた要素がクリックされた時、その要素のhref属性の値がついた箇所に移動するという処理をします。


$(".goSection").on("click", function() {

    // クリックされた要素のhref属性の値を取得 例:#first
    const scrollTarget = $(this)[0].attributes[1].nodeValue;

    // 取得した値のid属性がついた要素の位置を取得
    const offsetTop = $(scrollTarget).offset().top;

    // 取得した箇所に移動
    $("html, body").animate({ scrollTop: offsetTop }, 200);

    return false;
});

以上です。

6
3
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
6
3