jqueryによるスムーズスクロールのメモ

まず先にjquery-3.1.1.min.jsを読み込む
<script type='text/javascript' src='http://xxxx.jp/js/jquery-3.1.1.min.js'></script>

jqueryの設定は以下
jQuery(function($){
$('a[href^="#"]').click(function() {
// クリックした要素のhref属性の値を取得
var anchor = $(this).attr('href');
// 表示位置を取得
var position = $(anchor).offset().top-20;
// アニメーションの効果の作成
$('body,html').animate({ scrollTop : position }, 500, 'swing');
return false;
});
});

<a href="#koko">#kokoというidのところへスクロールする</a>

<span id="koko">このidの付いた要素へスクロールしてくる</span>
記事id:860 / 3392PV

関連記事