LoginSignup
0
0

More than 3 years have passed since last update.

ページ内ジャンプ

Posted at

ページ内ジャンプとは

ページ内(シングルページ等で使い勝手が良い)で更新せずにダウンスクロールで指定した要素に飛ばしてくれる機能。

⚠️下の「ここをクリック!」は画像の為実際に押せません

565a83a908b7b8ae4f73ca0ed734fdc7.png
ヌルッと指定の要素へ⬇️
c9f9e31159d77b59c602738a7be35bbb.png

HTMLの記述

ジャンプボタン
<a href="#sample">ここをクリック</a>
ジャンプ先(アンカー)
<h2 id="sample">これは見出しです</h2>

コードで使い方を説明

sample.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>sample</title>
  </head>
  <body>
    <h1>page内ジャンプの使い方</h1>
    <p>
      <a href="#link">クリックすると飛びます</a>
    </p>
    <p style="padding-top: 1000px">
      <a name="link">ジャンプ先です</a>
    </p>
  </body>
</html>

飛ばす速度(スクロール速度)を調整する

①HTML

html
<a href='#target'>Topへ戻る</a>

②jQuery

jQuery
// ページ内リンクのみ取得します。
$('a[href^=#]').click(function(){
    //デフォルトのイベントをキャンセル
    event.preventDefault();

    // 移動先となる要素を取得します。
    var target = $(this.hash);
    if (!target.length) return;

    // 移動先の位置を取得します
    var targetY = target.offset().top;

    // animateで移動します
    $('body').animate({scrollTop: targetY}, 500, 'swing');
});

速度調整

jQuery
var targetY = target.offset().top - 50;

倍速でスクロール

jQuery
$('body').animate({scrollTop: targetY}, 1000, 'swing');

画面内スクロールはシングルページでかなり使えますし、UIの使い勝手を考えた素晴らしい技術なのでおすすめです!

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