Skip to content

Instantly share code, notes, and snippets.

@HituziANDO
Last active April 6, 2016 04:01
Show Gist options
  • Save HituziANDO/387bb3de6d2a68b9de0d to your computer and use it in GitHub Desktop.
Save HituziANDO/387bb3de6d2a68b9de0d to your computer and use it in GitHub Desktop.
/**
* @version 1.0.4
* @require jQuery 1.0+
*/
(function ($) {
/**
* @param opts
* disable: trueならばスクロールを無効にする
* duration: 'fast','slow'またはミリ秒
* offsetTop: ビューより上部の余白分
* isBottomBase: trueならばビューが画面外に出た時にスクロールする。falseならばビューの上端が画面上端に達した時にスクロールする
*/
$.fn.follow = function (opts) {
opts = opts || {};
$.extend({
disable: false,
duration: 'fast',
offsetTop: 0,
isBottomBase: false
}, opts);
if (opts.disable) return;
var $obj = $(this);
var offsetTop = $obj.offset().top;
var $window = $(window);
$window.scroll(function () {
var scrollTop = $window.scrollTop();
var basePos;
var marginTop;
if (opts.isBottomBase) {
basePos = $obj.outerHeight();
var ex = scrollTop % ($obj.outerHeight() + offsetTop);
marginTop = scrollTop - ex - offsetTop + opts.offsetTop;
} else {
basePos = 0;
marginTop = scrollTop - offsetTop + opts.offsetTop;
}
var x = scrollTop % ($obj.outerHeight() + offsetTop);
if (scrollTop > offsetTop + basePos) {
$obj.stop().animate({
marginTop: marginTop
}, {
duration: opts.duration,
complete: function () {}
});
} else {
$obj.stop().animate({
marginTop: 0
}, {
complete: function () {}
});
}
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment