Skip to content

Instantly share code, notes, and snippets.

@shiromatakumi
Last active February 24, 2016 07:09
Show Gist options
  • Save shiromatakumi/481edebe5e743d306a2d to your computer and use it in GitHub Desktop.
Save shiromatakumi/481edebe5e743d306a2d to your computer and use it in GitHub Desktop.
はてなブログのサイドバーを固定
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(window).load(function (){
// 変数の設定
// サイドバーの一番最後のモジュール
var $module = $('.hatena-module:last');
var modulePosition = $module.offset().top;
var moduleHeight = $module.outerHeight(true);
// サイドバー全体
var $sidebar = $('#box2');
var sidebarPosition = $sidebar.offset().top;
var sidebarHeight = $sidebar.outerHeight();
var sidebarWidth = $sidebar.width();
// メインコンテンツ
var $main = $('#main');
var mainHeight = $main.outerHeight();
var mainBottom = $main.offset().top + $main.outerHeight();
// サイドバーを固定にする関数
function fixedLastModule(){
// メインコンテンツよりサイドバーが長い場合は無効化
if(sidebarHeight > mainHeight){return;}
// リサイズされた時のためにサイドバーの位置を再取得
mainBottom = $main.offset().top + $main.outerHeight();
sidebarPosition = $sidebar.offset().top;
// 2カラムで、モジュールの一番最後までスクロールされたらCSSの書き換え
if(mainBottom >= sidebarPosition && $(window).scrollTop() > modulePosition) {
$module.css({
'position': 'fixed',
'top': '10px', //ここの数値を変更して固定位置を調整して下さい。
'width': sidebarWidth
});
} else {
$module.css({
'position': '',
'top': '',
'width': ''
});
}
// フッターの位置まで来たらストップ
// 高さの設定
var bodyHeight = $('body').outerHeight();
var windowHeight = $(window).outerHeight();
var footerHeight = $('#footer').outerHeight();
var scrollBottom = bodyHeight - windowHeight - footerHeight;
if(moduleHeight > windowHeight - footerHeight){
if(mainBottom > sidebarPosition && $(window).scrollTop() >= scrollBottom){
$('#content').css({
'position': 'relative'
});
$module.css({
'position': 'absolute',
'top': '',
'bottom': 0
});
} else {
$('#content').css({
'position': ''
});
$module.css({
'bottom': ''
});
}
}
}
// イベントの設定
$(window).scroll(fixedLastModule);
$('body').on('touchmove', fixedLastModule);
$(window).resize(fixedLastModule);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment