Skip to content

Instantly share code, notes, and snippets.

@nissuk
Created October 30, 2011 08:00
Show Gist options
  • Save nissuk/1325688 to your computer and use it in GitHub Desktop.
Save nissuk/1325688 to your computer and use it in GitHub Desktop.
jQuery: smoothScroll
/**
* jQuery smoothScroll
* ページ内リンクをブラウザの挙動に近い形でスムーズにスクロールします。
*
* # 使用例
* $("a").smoothScroll();
* $("a").smoothScroll({ duration: "fast", easing: "swing" });
*
* # TODO
* - vertical-alignがtopでないimgを持つaに移動する際上部の位置がずれる点の修正
*/
(function($){
var pluginName = "smoothScroll";
var plugin = function(options){
var settings = $.extend({}, plugin.defaults, options);
var complete = settings.complete || function(){};
var live = settings.live;
delete settings.live;
return this[ live ? "live" : "bind" ]("click", function(){
// 同一ページ内のリンクでない場合は処理を中断します。
if (!inPage(this.href)) return;
// 同一ページでも「#」がなければリクエストが投げられるべきなので処理を中断します。
// HTMLAnchorElement#hashだと「#」だけのときと「#」自体ないときの違いがわからないのでここで判定します。
if (this.href.indexOf("#") == -1) return;
var hash = this.hash;
var target;
// フラグメント識別子が空(「#」だけ)の場合は最上部に移動すべきなのでhtmlを対象にします。
// 対象のIDを持つ要素が取得できない場合は移動せずその場に留まるべきなので処理を中断します。
if (hash == "") {
target = $("html");
} else {
target = $(hash);
if (target.length <= 0) return;
}
var perSettings = $.extend({}, settings, {
complete: function(){
complete.apply(this, arguments);
location.hash = hash;
}
});
var offset = target.offset();
var top = offset.top;
var left = offset.left;
$("html, body").stop(true).animate({ scrollTop: top, scrollLeft: left }, perSettings);
return false;
});
};
plugin.defaults = {
live: true,
duration: "slow"
};
$.fn[pluginName] = plugin;
/**
* 同一ページ内のリンクかどうかを判別します。
*/
var inPage = function(href){
return href.split("#")[0] == location.href.split('#')[0];
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment