前提・実現したいこと
ハンバーガーボタンのメニュー以外のエリア(またはメニューのリンク先)を押した時に
メニューが閉じるようにしたいです。
発生している問題・エラーメッセージ
スマホで動きませんでした。(iPhone7 plusのsafariで確認済)
PCでは普通に動きます。
該当のソースコード
HTML
1 <div id="test"> 2 3 <div id="mobile-nav"> 4 <a class="menu-trigger"> 5 <span></span> 6 <span></span> 7 <span></span> 8 </a> 9 <nav class="g-nav"> 10 <ul class="list"> 11 <li class="item"><a href="#">test</a></li> 12 <li class="item"><a href="#">test</a></li> 13 <li class="item"><a href="#">test</a></li> 14 </ul> 15 </nav> 16 </div> 17 18 </div>
JS
1$(function(){ 2 $('.menu-trigger').on('click',function(){ 3 $(this).toggleClass('active'); 4 $('.g-nav').slideToggle(); 5 }); 6}); 7 8//閉じる 9$('#test').on('click touchend', function(e){ 10 if (!$(e.target).closest('.menu-trigger').length) { 11 $('.g-nav').fadeOut(1000); 12 $('.menu-trigger').removeClass('active'); 13 } 14});
CSS
1.menu-trigger, 2.menu-trigger span{ 3 position: absolute; 4 left: 0; 5 box-sizing: border-box; 6 cursor :pointer; 7} 8.menu-trigger{ 9 position: relative; 10 width: 50px; 11 height: 50px; 12 z-index: 1000; 13} 14.menu-trigger span{ 15 position: absolute; 16 background: #28333b; 17 width: 30px; 18 height: 2px; 19 left: 0; 20 right: 0; 21 margin: auto; 22} 23.menu-trigger span:nth-of-type(1){ 24 top: 15px; 25} 26.menu-trigger span:nth-of-type(2){ 27 top: 0; 28 bottom: 0; 29} 30.menu-trigger span:nth-of-type(3){ 31 bottom: 15px; 32} 33.menu-trigger.active span:nth-of-type(1){ 34 -webkit-transform: translateY(9px) rotate(-45deg); 35 transform: translateY(9px) rotate(-45deg); 36} 37.menu-trigger.active span:nth-of-type(2){ 38 opacity: 0; 39} 40.menu-trigger.active span:nth-of-type(3){ 41 -webkit-transform: translateY(-9px) rotate(45deg); 42 transform: translateY(-9px) rotate(45deg); 43} 44 45.g-nav { 46 display: none; 47 position: absolute; 48 top: 0; 49 left: 0; 50 right: 0; 51 margin: 0 auto; 52 text-align:center; 53 background-color: rgba(65,76,82,0.90); 54 width: 70%; 55 overflow-y:scroll; 56} 57 58.g-nav .list { 59 display: inline-block; 60 padding: 20px; 61} 62 63.g-nav .list .item { 64 text-align: left; 65 margin-bottom: 10px; 66} 67.g-nav .list .item a { 68 text-decoration: none; 69 color: #fff !important; 70 padding: 5px 0; 71}
試したこと
「$(document).on、$('body').on」という書き方だと上手くいかないとみかけたため、bodyの下にdiv#testを作ってjsの書き方を変更
・div#testに「cursor: pointer;」を指定(リンク箇所以外もカーソルの形が変わって見づらいことと、動作しなかったので削除)
・「click touchend」ではなく「touchend」にする(動作せず)
・「Hammer.js」の使用(上手くいかなかったので削除)
回答1件
あなたの回答
tips
プレビュー