jQueryを使わずにslideToggleする
公開日:
最終更新日:
実際jQueryはコピーを作って、どうこうと色々やってるみたいなのですが、
とりあえずcssとjsでサクッと出来る感じのです。
slideToggle(開閉ボタン)
サンプル
- a
- aaaaaaaaaa
ccccc - b
- bbbbbbbbbb
- c
- cccccccccccc
Html
1 2 3 4 5 6 7 8 |
<dl class="toggle"> <dt class="toggleInner">a</dt> <dd>aaaaaaaaaa</dd> <dt class="toggleInner">b</dt> <dd>bbbbbbbbbb</dd> <dt class="toggleInner">c</dt> <dd>cccccccccccc</dd> </dl> |
Css
1 2 3 4 |
dl.toggle dd { overflow: hidden; transition: .2s; } |
Javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
const toggleInner = document.getElementsByClassName('toggleInner'); let nextdd; let nextddH = []; let hinsert; let toggleLoop = (i) => { nextddH[i] = toggleInner[i].nextElementSibling.clientHeight; toggleInner[i].nextElementSibling.style.height = '0px'; toggleInner[i].addEventListener('click', () => { nextdd = toggleInner[i].nextElementSibling; if (nextdd.style.height !== '0px') { nextdd.style.height = '0px'; } else { nextdd.style.height = nextddH[i] + 'px'; } }, false); }; for (let i = 0; i < toggleInner.length; i++) { toggleLoop(i); } |
IE11対応バージョン(Babelした)
Javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
'use strict'; var toggleInner = document.getElementsByClassName('toggleInner'); var nextdd = void 0; var nextddH = []; var hinsert = void 0; var toggleLoop = function toggleLoop(i) { nextddH[i] = toggleInner[i].nextElementSibling.clientHeight; toggleInner[i].nextElementSibling.style.height = '0px'; toggleInner[i].addEventListener('click', function () { nextdd = toggleInner[i].nextElementSibling; if (nextdd.style.height !== '0px') { nextdd.style.height = '0px'; } else { nextdd.style.height = nextddH[i] + 'px'; } }, false); }; for (var i = 0; i < toggleInner.length; i++) { toggleLoop(i); } |
よろしければコメントをどうぞ