最近HTML、CSS、jQueryを学び始めた初心者です。
こちらのサイト様の記事を参考に、サイト内でアコーディオンメニューを実装しています。
http://www.webmoyou.sakura.ne.jp/web/124/
画面サイズが640px以下の場合はアコーディオンメニュー、それ以上の場合はメニューを全て展開し折りたたまないような仕様にしたいのですが、上手く実装ができません。
###該当のソースコード
html
1<div class="accordion"> 2 <p class="switch">タイトル</p> 3 <div class="contentWrap displayNone"> 4 <ul> 5 <li><a href="test.html">テスト</a></li> 6 <li><a href="test.html">テスト</a></li> 7 <li><a href="test.html">テスト</a></li> 8 </ul> 9 </div> 10</div>
css
1.displayNone { 2display: none; 3} 4.accordion li { 5border-bottom: 1px solid #ccc; 6padding: 10px; 7} 8.accordion a { 9display: block; 10} 11.contentWrap { 12margin: 10px; 13} 14.switch { 15cursor:pointer; 16font-weight: bold; 17padding:10px 40px 10px 10px; 18font-size: 14px; 19background: #eee; 20border-bottom: 1px solid #ccc; 21position: relative; 22} 23 24.switch:after { 25content: ">"; 26position: absolute; 27right: 10px; 28top: -100%; 29bottom: -100%; 30margin: auto; 31font-size: 16px; 32height: 16px; 33-moz-transform: rotate(90deg); 34-ms-transform: rotate(90deg); 35-webkit-transform: rotate(90deg); 36transform: rotate(90deg); 37font-family: sans-serif; 38} 39.switch.open:after { 40content: "x"; 41}
javascript
1(function($) { 2 // 読み込んだら開始 3 $(function() { 4 // アコーディオン 5 var accordion = $(".accordion"); 6 accordion.each(function () { 7 var noTargetAccordion = $(this).siblings(accordion); 8 $(this).find(".switch").click(function() { 9 $(this).next(".contentWrap").slideToggle(); 10 $(this).toggleClass("open"); 11 noTargetAccordion.find(".contentWrap").slideUp(); 12 noTargetAccordion.find(".switch").removeClass("open"); 13 }); 14 }); 15 }); 16})(jQuery);
###試したこと
javascript
1$(function() { 2 var w = $(window).width(); 3 var x = 640; 4 if (w >= x) { 5 $("div").removeClass("accordion"); 6 }); 7 } 8});
jQueryで特定の画面サイズ以下になった際に、アコーディオンに関連するクラスを全て取り払えばいいと思ったのですが、アコーディオンメニューが残ったままになってしまいます。
このような場合にはどのように対処すべきか、またはもっと上手いコードの書き方について、
皆様の知恵を貸していただけると幸いです。
回答2件
あなたの回答
tips
プレビュー