ブログとか縦長のサイトで下にスクロールしまくってもサイドバーのコンテンツを追跡表示しつづけるあれ
jQueryプラグインにした。あとでプロジェクトにまとめてgithubにUPしよう。
(function($) { $.fn.track = function(offset) { offset = offset || 0; this.each(function() { var self = $(this); var initialCss = { position: self.css("position"), top: self.css("top"), width: self.css("width") }; var width = self.css("box-sizing") === "border-box" ? self.outerWidth() : self.width(); var offsetTop = self.offset().top - offset - parseInt(self.css("margin-top")); var offsetLeft = self.offset().left; $(window).scroll(function() { self.css($(this).scrollTop() > offsetTop ? { position: "fixed", top: offset, left: offsetLeft - $(this).scrollLeft(), width: width } : initialCss); }); }); }; })(jQuery);
特定の位置までスクロールされると該当要素のpositionをfixedに変更するのが基本なんだけど、fixedにしたときにtopプロパティがautoのままではまずいのと、widthがautoまたは%指定のように親要素に依存する設定ではまずいということで、その辺りをごにょっと。