ページ内ジャンプとは
ページ内(シングルページ等で使い勝手が良い)で更新せずにダウンスクロールで指定した要素に飛ばしてくれる機能。
⚠️下の「ここをクリック!」は画像の為実際に押せません
HTMLの記述
ジャンプボタン
<ahref="#sample">ここをクリック!</a>
ジャンプ先(アンカー)
<h2id="sample">これは見出しです。</h2>
コードで使い方を説明
sample.html
<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>sample</title></head><body><h1>page内ジャンプの使い方</h1><p><ahref="#link">クリックすると飛びます</a></p><pstyle="padding-top: 1000px"><aname="link">ジャンプ先です</a></p></body></html>
飛ばす速度(スクロール速度)を調整する
①HTML
html
<ahref='#target'>Topへ戻る</a>
②jQuery
jQuery
// ページ内リンクのみ取得します。$('a[href^=#]').click(function(){//デフォルトのイベントをキャンセルevent.preventDefault();// 移動先となる要素を取得します。vartarget=$(this.hash);if(!target.length)return;// 移動先の位置を取得しますvartargetY=target.offset().top;// animateで移動します$('body').animate({scrollTop:targetY},500,'swing');});
速度調整
jQuery
vartargetY=target.offset().top-50;
倍速でスクロール
jQuery
$('body').animate({scrollTop:targetY},1000,'swing');