恐ろしく多機能なjQuery.easingプラグイン
jQuery.easingプラグインを利用してスムーススクロールを簡単導入
前回はSmooth-scroll.jsライブラリでスムーススクロールを導入する方法をまとめましたが、今回はjQuery.easingプラグインを使用したスムーススクロールの導入です。
個人的にとてもよく使うプラグインです。JQuery環境が必須なので併せてセットアップします。
設置方法
ライブラリをダウンロードしサイトへ設置します。
jQuery
https://jquery.com/download/
jQuery Easing
https://github.com/gdsmith/jquery.easing
CDNも利用できるので、環境に合わせて選びます。
jQuery
https://code.jquery.com/
jQuery Easing
https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js
リンクを設置します。
使用したいアンカーリンクにクラス「class=”js-scroll-trigger”」を付与します。
<a class="js-scroll-trigger" href="#content1">リンク1</a>
<div id="content1"></div>
最後にコーディング。
jQuery Easingをコーディングします。
$('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html, body').animate({
scrollTop: (target.offset().top - 20)
}, 1000, "easeInOutExpo");
return false;
}
}
});
一行目でBootstrapのクラスと被らないようnot([href=”#”]) という書き方をしています。scrollTopはトップからの距離です。サイトにあわせて書き換えてください。
以上で作動すると思います。
jQuery Easingはさまざまな使い方ができるので、是非覚えておきたいプラグインです。
