はてなブログでスクロール途中で固定配置になるサイドバーを作る
イメージ
下のデモでは、スクロールすると途中で右エリアが固定配置になっている・・・ハズ。
See the Pen fixedPosHateblo by nju33 (@nju33) on CodePen.
コレをはてなブログのサイドバーでも同じことができるようにしてみたいと思います。
確認デザインテーマ
とりあえず次の公式のデザインテーマで確認したら使えてました。
- Novel
- Report
コード
基本的に、下記のコードをデザイン設定→カスタマイズ→フッタへコピペするだけで使えます。
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> (function($) { $(function() { $.fn.fixedPosHateblo = function(px) { var $this, $win, height, isLowerThanOffset, isSeeBottom, thisWidth, toggleFixed, topOrBottom; px || (px = 0); $win = $(window); $this = $(this); height = { box2Inner: $this.height(), offset: (function() { var $tgt, result; $tgt = $this; result = $this.offset().top; while (!$tgt.offsetParent().is('html')) { $tgt = $tgt.offsetParent(); result += $tgt.offset().top; } return result; })(), getSum: function() { return this.box2Inner + this.offset; } }; topOrBottom = innerHeight > height.getSum() ? 'top' : 'bottom'; isLowerThanOffset = function() { return ($win.scrollTop() + px) > height.offset; }; isSeeBottom = function() { return (innerHeight + $win.scrollTop() - px) > height.getSum(); }; toggleFixed = function(condition) { if (condition) { return this.css('position', 'fixed'); } else { return this.css('position', 'static'); } }; $this.css('width', $this.width()); $this.css(topOrBottom, px != null ? px : 0); $win.scroll(function() { return toggleFixed.call($this, topOrBottom === 'top' ? isLowerThanOffset() : isSeeBottom()); }); }; $('#box2-inner').fixedPosHateblo(100); }); })(jQuery); </script>
+1
46行目の.fixedPosHateblo(100);
にある数値を変更すると、固定配置になった時の位置をカスタマイズできます。
例えば100とした場合、固定配置になった時サイドバー下に100pxの隙間を取ります。
でももし、サイドバーが全部画面に表示されるほど高さが低い時は、隙間をサイドバーの上に取って上に詰めて表示するようにしてます。
よかったら使ってみてねー!