ハンバーガーメニューの実装 (by yachin29)
<nav> <div id="btn">
<span id="hum"></span>
</div> <ul> <li><a href="#">Home</a></li> <li><a href="#">Shop</a></li> <li><a href="#">Collections</a></li> <li><a href="#">Philosophy</a></li> <li><a href="#">Press</a></li> <li><a href="#">About</a></li> </ul> </nav>
@media screen and (max-width:767px){ #btn { width: 40px; height: 40px; border: 1px solid #000; border-radius: 4px; position: relative; margin-left: 20px; } #hum { display: block; width: 30px; height: 2px; background: #000; position: absolute; top:0; right: 0; bottom: 0; left: 0; margin: auto; transition: 0.2s; } #hum:before { display: block; content: ""; width: 30px; height: 2px; background: #000; position: absolute; top:-20px; right: 0; bottom: 0; left: 0; margin: auto; transition: 0.2s; } #hum:after { display: block; content: ""; width: 30px; height: 2px; background: #000; position: absolute; top:0; right: 0; bottom: -20px; left: 0; margin: auto; transition: 0.2s; } #hum.click { background: transparent; } #hum.click:before { top:0; transform: rotate(45deg); } #hum.click:after { bottom: 0; transform: rotate(135deg); } nav ul { width:100%; position: fixed; top: 60px; padding-left: 10px; background:#f0ede7; display: none; } nav li { float:none; width:100%; line-height: 30px; } nav li a { text-align:left; } nav li a:hover { border-bottom: none; padding-bottom:0; } header.fixed h1 { display: none; } }
// JavaScript Document $(function() { if(window.innerWidth > 767){ $(window).scroll(function() { if ($(window).scrollTop() > 10) { $('header').addClass('fixed').slideDown(900); } else { $('header').removeClass('fixed'); } }); } $('#btn').on('click touchstart',function(){ $('#hum').not(':animated').toggleClass('click'); $('nav ul').not(':animated').slideToggle(200); }); });
修正後のjQuery
// JavaScript Document $(function() { if(window.innerWidth > 767){ var $header = $('header'); $(window).scroll(function() { if ($(window).scrollTop() > 160) { $header.addClass('fixed'); } else { $header.removeClass('fixed'); } }); } $('#btn').on('click touchstart',function(){ if($(window).innerWidth() <= 767){ $('#hum').not(':animated').toggleClass('click'); $('nav ul').not(':animated').slideToggle(200); }; }); $(window).resize(function(){ $('nav ul').hide();//スマホの時 if($(window).innerWidth() > 768){ $('nav ul').show();//タブレット以上の時 $('#hum').removeClass('click');//PCから戻る時に邪魔な.clickを削除するため } }); });