この記事は2017年6月13日に書かれたもので、内容が古い可能性がありますのでご注意ください。
以前の記事「スマホサイドメニュープラグイン「sidr」にヘッダー固定を追加」にブラウザ間で不具合が見られたので、今回はプラグインなしでドロワーメニューを実装する方法をご紹介します。
HTML
<div id="wrapper"> <header> <div id="simple-menu"> <div class="navicon-line"></div> <div class="navicon-line"></div> <div class="navicon-line"></div> </div> </header> <div id="contents"> ~メインコンテンツ~ </div> </div><!-- #wrapper --> <div id="slide"> <ul> <li><a href="#anc_1">List 1</a></li> <li><a href="#anc_2">List 2</a></li> <li><a href="#anc_3">List 3</a></li> </ul> </div>
headerにドロワー開閉用のハンバーガーボタンを設置します。id”slide”内にドロワー用のHTMLを記述します。
CSS
header{ padding: 20px; background-color: #000; overflow: hidden; position: fixed; top: 0; left: 0; width: 100%; z-index: 2; } #simple-menu { width: 28px; height: auto; float: left; } .navicon-line { background-color: #FFF; border-radius: 1px; height: 4px; margin-bottom: 3px; width: 24px; } #contents{ padding: 66px 15px 0 15px; } #slide { position: fixed; width: 260px; height: 100%; z-index: 2; top: 0; left: -260px; } ul{ margin: 0 0 30px 0; overflow: hidden; } li a { border-bottom: 1px solid #ccc; padding: 10px; display: block; }
jQuery
//ドロワー開閉 $('#simple-menu').click(function(){ if($(this).attr("class")=="headOpen"){ $('header').animate({left: '0'}, 200); $('#contents').animate({marginLeft: '0'}, 200); $('#slide').animate({left: '-260px'}, 200); $(this).removeClass("headOpen"); }else{ $('header').animate({left: '260px'}, 200); $('#contents').animate({marginLeft: '260px'}, 200); $('#slide').animate({left: '0'}, 200); $(this).addClass("headOpen"); } }); //ページ内リンク var headerHight = 80; $('#slide a[href^=#]').click(function(){ var href = $(this).attr("href"); var target = $(href == "#" || href == "" ? 'html' : href); var position = target.offset().top-headerHight; $('html,body').animate({ scrollTop: position }, 'fast'); return; });
ハンバーガーボタンをクリックした時の挙動(//ドロワー開閉)とドロワーメニューでアンカーリンクをクリックした時の挙動(//ページ内リンク)を記載しています。
デモページを作成しましたのでこちらからご確認ください。
DEMO