780 views
この記事は最終更新から 1294日 が経過しています。
1. やりたいこと
ページ内リンクを押下時、ページ内移動をスムーズに見せたい。
2. やってみる
HTML
<a class="jumpitem" href="#ZZZ">LINK</a> : <h1 id="ZZZ">Item 1</h1>
JavaScript
$('a.jumpitem').on('click',function(){
var id = $(this).attr('href');
// 移動先のY座標を取得
var trgetPosY = $(id).offset().top;
// スクロールして移動 (500ms)
$('body,html').animate({scrollTop:trgetPosY}, 500, 'swing');
return false; // 勝手にジャンプさせない。
});
3. 参考情報
・elem.offset()は、document (=最上位の親要素)を原点とした指定要素の位置情報を返す。
Description: Get the current coordinates of the first element in the set of matched elements, relative to the document.
https://api.jquery.com/offset/
アクセス数(直近7日): ※試験運用中、BOT除外簡易実装済2025-11-17: 2回 2025-11-16: 4回 2025-11-15: 4回 2025-11-14: 3回 2025-11-13: 3回 2025-11-12: 1回 2025-11-11: 2回