LoginSignup
18
18

More than 5 years have passed since last update.

要素をスクロール時にウィンドウ上部にひっかかるようにする jQuery プラグイン

Last updated at Posted at 2012-10-26

うまい表現がみつからないのですが、facebook のサイドバーとかのアレです。

jquery.headbutt.js
$.fn.headbutt = function (offset) {
  if (offset == null) {
    offset = 0;
  }
  this.each(function () {
    var $elem = $(this)
      , initialTop = $elem.offset().top
      , initialPosition = $elem.css('position')
    ;
    $window = $(window).on('scroll', function () {
      if ($window.scrollTop() > initialTop - offset) {
        $elem.css({ position: 'fixed', top: offset });
      } else {
        $elem.css({ position: initialPosition });
      }
    });
  });
};

こんな感じで使います。

$('#side-menu').headbutt();

固定レイアウトのヘッダーがあるような場合には、オフセットも設定できます。

$('#side-menu').headbutt($('#fixed-menu').height());

Gist にも貼っておきました。
https://gist.github.com/3957501

18
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
18