アコーディオンメニューの実装をしよう!
Share
こんなことを説明しています!
- アコーディオンメニューの作り方
- 余白やボーダーの付け方
- アイコンの回転方法
解説動画
コードの解説
HTMLの記述
<div class="inner"> <h2 class="title">アコーディオンメニューを実装しよう</h2> <div class="menu-wrap"> <div class="menu"> <div class="question"> 質問のテキスト質問のテキスト質問のテキスト </div> <div class="answer"> 回答のテキスト回答のテキスト回答のテキスト回答のテキスト回答のテキスト回答のテキスト回答のテキスト </div> </div> <div class="menu"> <div class="question"> 質問のテキスト質問のテキスト質問のテキスト </div> <div class="answer"> 回答のテキスト回答のテキスト回答のテキスト回答のテキスト回答のテキスト回答のテキスト回答のテキスト </div> </div> <div class="menu"> <div class="question"> 質問のテキスト質問のテキスト質問のテキスト </div> <div class="answer"> 回答のテキスト回答のテキスト回答のテキスト回答のテキスト回答のテキスト回答のテキスト回答のテキスト </div> </div> </div> </div>
CSSの記述
// ==================== // レイアウトを整えるcss // ==================== .inner { width: 100%; max-width: 1400px; margin: auto; padding: 0 40px; } .title { font-size: 40px; font-weight: 700; margin: 80px 0; text-align: center; } .question { color: blue; font-size: 24px; line-height: 1.5; background: rgba(171, 245, 238, 0.233); } .answer { color: red; font-size: 16px; line-height: 1.5; background: rgba(247, 155, 155, 0.233); } // ==================== // 今回のテーマ // ===================== .menu { border-top: 1px solid #000; &:last-of-type { border-bottom: 1px solid #000; } &:hover { cursor: pointer; } } .question { padding: 20px 40px 20px 10px; position: relative; //縦棒 &::before { content: ''; position: absolute; top: 50%; transform: translateY(-50%); right: 28px; width: 2px; height: 20px; background: #000; transition: all 0.3s ease; } //横棒 &::after { content: ''; position: absolute; top: 50%; transform: translateY(-50%); right: 20px; width: 20px; height: 2px; background: #000; } } .answer { padding: 20px 10px; display: none; border-top: 1px dashed red; } //開いているとき .menu.js-open { .question::before { transform: translateY(-50%) rotate(90deg); } }
ポイント
- 開閉両方を意識して余白や枠線をつける!
▶︎ 余白はquestionとanswerそれぞれにつける
▶︎ borderはmenuにつける - 擬似要素を使って + と - のアイコンを作る
▶︎今回は、棒が回転して + → - になるようにしたいので、content に書かず "棒" として処理 - js-open がついた時の処理を記述
▶︎ html に js-openを書いて作業
▶︎ menuにjs-openを当てておいて、その中にopen時の処理を書く
jQueryの記述
jQuery(function($){ $('.menu').on('click', function () { $(this).toggleClass('js-open'); $(this).children('.answer').slideToggle(); return false; }); });
ポイント
- クリックしたmenuに対してjs-openのつけ外し
- クリックしたmenuの子要素のanswerにslideToggleでanswer要素の出し入れ
▶︎ slideDown( ) 発火時に自動で display: block がつくので、js-open時の display: block の記述は不要
解説で使用したスニペット
scss.json
"before": { "prefix": "before", "body": [ "&::before {", " content: '';", " position: absolute;", "}", ], "description": "" },
"after": { "prefix": "after", "body": [ "&::after {", " content: '';", " position: absolute;", "}", ], "description": "" },
"top50": { "prefix": "top-50%", "body": [ "top: 50%;", "transform: translateY(-50%);", ], "description": "" },
javascript.json
"click": { "prefix": "click", "body": [ "\\$('$1').on('click', function () {", " $2", " return false;", "});", ], "description": "クリックイベント" },